本文介绍了后台工作者和Progressbar无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试在我的代码中实现后台工作程序和progreesbar.但是无法正常工作

我的代码如下.

Hi All,

I am trying to implement background worker and progreesbar in my code.But not working properly

My Code is as below.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.Collections;
namespace CompareSuite
{
    public partial class Form1 : Form
    {
        //int lastrow1;
        Hashtable myHashtable;
        private bool _isDirty;
        public Form1()
        {
            InitializeComponent();
            _isDirty = true;
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DialogResult resDialog = openFileDialog1.ShowDialog();
            if (resDialog.ToString() == "OK")
            {
                textBox1.Text = openFileDialog1.FileName;
            }
        }
        private void btnCompare_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" | textBox2.Text == "")
            {
                MessageBox.Show("Comparing needs two files", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            else
            {
                try
                {
                    btnCompare.Enabled = false;
                    btnCompare.BackColor = SystemColors.Control;
                    btnCompare.ForeColor = SystemColors.Control;
                    toolStripProgressBar1.Visible = true;
                    backgroundWorker1.WorkerReportsProgress = true;
                    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
                    backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
                    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
                    backgroundWorker1.RunWorkerAsync();

                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message);

                }
            }
        }
        private void ExcelCompare()
        {
            CheckExcellProcesses();
            string path = textBox1.Text;
            string path1 = textBox2.Text;
            string Filename = path.Substring(path.LastIndexOf('\\') + 1);
            string Filename1 = path1.Substring(path.LastIndexOf('\\') + 1);
            string textpath = textBox1.Text.Substring(0, textBox1.Text.Length - Filename.Length);
            string fileloc = textpath + "New.MAS";
            Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(path, 0, true, 1, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(path, 0, true, 0, "", "", "", "", "", "", "", 0, "", "", "");
            Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
            Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
            //Range last = workSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell,Type.Missing);
            //Range wrange = workSheet.get_Range("A1",last);
            Range r1 = ((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1]).EntireColumn;
            r1.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
            Range r2 = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1];
            r2.Select();
            r2.FormulaR1C1 = "=LEFT(RC[1],100)";
            r2.Select();
            Range r3 = (Microsoft.Office.Interop.Excel.Range)workSheet.get_Range("A1", "A160237");
            r2.AutoFill(r3, XlAutoFillType.xlFillCopy);
            r3.Copy(Type.Missing);
            sheets.Add(Type.Missing, workSheet, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheetA = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(2);
            Range r4 = (Microsoft.Office.Interop.Excel.Range)workSheetA.Cells[1, 1];
            r4.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            r4 = ((Microsoft.Office.Interop.Excel.Range)workSheetA.Cells[1, 1]).EntireColumn;
            r4.Select();
            r4.TextToColumns(r4, XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierNone, false, true, false, false, false, true, "|", Type.Missing, Type.Missing, Type.Missing, true);
            Range r5 = ((Microsoft.Office.Interop.Excel.Range)workSheetA.Cells[1, 3]).EntireColumn;
            r5.Copy(Type.Missing);
            workSheet.Select(Type.Missing);
            Range o = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, 1];
            o.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            Range data = (Microsoft.Office.Interop.Excel.Range)workSheet.get_Range("A1", "B1").EntireColumn;
            theWorkbook.Names.Add("data", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, "=" + Filename + "!C1:C2", Type.Missing);
            workSheetA.Select(Type.Missing);
            r5.Copy(Type.Missing);
            Microsoft.Office.Interop.Excel.Application ExcelObj1 = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook theWorkbook1 = ExcelObj1.Workbooks.Open(path1, 0, true, 1, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets sheets1 = theWorkbook1.Worksheets;
            Microsoft.Office.Interop.Excel.Worksheet workSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)sheets1.get_Item(1);
            sheets1.Add(Type.Missing, workSheet1, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheet1A = (Microsoft.Office.Interop.Excel.Worksheet)sheets1.get_Item(2);
            Range r6 = (Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1, 1];
            r6.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            Range r7 = ((Microsoft.Office.Interop.Excel.Range)workSheet1.Cells[1, 1]).EntireColumn;
            r7.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
            Range r8 = (Microsoft.Office.Interop.Excel.Range)workSheet1.Cells[1, 1];
            //r8.Select();
            r8.FormulaR1C1 = "=LEFT(RC[1],100)";
            //r8.Select();
            Range r9 = (Microsoft.Office.Interop.Excel.Range)workSheet1.get_Range("A1", "A160237");
            r8.AutoFill(r9, XlAutoFillType.xlFillCopy);
            r9.Copy(Type.Missing);
            sheets1.Add(Type.Missing, workSheet1A, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheet1B = (Microsoft.Office.Interop.Excel.Worksheet)sheets1.get_Item(3);
            Range r10 = (Microsoft.Office.Interop.Excel.Range)workSheet1B.Cells[1, 1];
            r10.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj1.CutCopyMode = XlCutCopyMode.xlCopy;
            r10 = ((Microsoft.Office.Interop.Excel.Range)workSheet1B.Cells[1, 1]).EntireColumn;
            r10.Select();
            r10.TextToColumns(r10, XlTextParsingType.xlDelimited, XlTextQualifier.xlTextQualifierNone, false, true, false, false, false, true, "|", Type.Missing, Type.Missing, Type.Missing, true);
            Range r11 = ((Microsoft.Office.Interop.Excel.Range)workSheet1B.Cells[1, 3]).EntireColumn;
            r11.Copy(Type.Missing);
            Range r12 = ((Microsoft.Office.Interop.Excel.Range)workSheet1.Cells[1, 1]).EntireColumn;
            r12.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            //theWorkbook1.SaveAs("D:\\MAS\\Rameel.xlsx", XlFileFormat.xlXMLSpreadsheet, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            //theWorkbook1.SaveCopyAs("D:\\MAS\\rameel.xlsx");
            //ExcelObj1.Save("D:\MAS\rameel.xls");
            ExcelObj1.CutCopyMode = XlCutCopyMode.xlCopy;
            Range data1 = (Microsoft.Office.Interop.Excel.Range)workSheet1.get_Range("A1", "B1").EntireColumn;
            //r13.Select();
            theWorkbook1.Names.Add("data1", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, "=" + Filename1 + "!C1:C2", Type.Missing);
            workSheet1A.Select(Type.Missing);
            r6.Select();
            r6.EntireColumn.ColumnWidth = 17.43;
            Range r14 = (Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1, 2];
            r14.Select();
            r14.FormulaR1C1 = "=VLOOKUP(RC[-1],data1,2,FALSE)";
            Range last1 = ((Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1, 1]).SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
            Range R15 = workSheet1A.get_Range("B1", last1);
            r14.AutoFill(R15, XlAutoFillType.xlFillCopy);
            r14.EntireColumn.Select();
            //ro.Insert(XlInsertShiftDirection.xlShiftDown, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
            r14.AutoFilter(2, Type.Missing, XlAutoFilterOperator.xlOr, "#N/A", Type.Missing);
            Range ro = (Microsoft.Office.Interop.Excel.Range)workSheet1A.Cells[1,2];
            ro.Select();
            if ((string)ro.Text!="#N/A")
            {
                MessageBox.Show("No new items available");
                KillExcel();
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Visible = false;
                return;
            }
            //r6.Select();
            r6.EntireColumn.Select();
            r6.EntireColumn.Copy(Type.Missing);
            sheets.Add(Type.Missing, workSheetA, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet workSheetB = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(3);
            Range r17 = ((Microsoft.Office.Interop.Excel.Range)workSheetB.Cells[1, 1]);
            r17.ColumnWidth = 26.71;
            r17.PasteSpecial(XlPasteType.xlPasteValues, XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            Range r16 = (Microsoft.Office.Interop.Excel.Range)workSheetB.Cells[1, 2];
            r16.Select();
            r16.FormulaR1C1 = "=VLOOKUP(RC[-1],data,2,FALSE)";
            Range last = ((Microsoft.Office.Interop.Excel.Range)workSheetB.Cells[1, 1]).SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
            Range r18 = workSheetB.get_Range("B1", last);
            r16.AutoFill(r18, XlAutoFillType.xlFillCopy);
            r16.EntireColumn.Copy(Type.Missing);
            FileStream fs = null;
            if (!File.Exists(fileloc))
            {
                using (fs = File.Create(fileloc))
                {
                }
                System.IO.File.WriteAllText(fileloc, Clipboard.GetText());
            }
            ExcelObj.CutCopyMode = XlCutCopyMode.xlCopy;
            theWorkbook.Close(false, Type.Missing, false);
            theWorkbook1.Close(false, Type.Missing, false);
            ExcelObj.Quit();
            ExcelObj1.Quit();
            KillExcel();
            //lastrow1 = workSheet.UsedRange.Rows.Count;
            //theWorkbook.SaveAs(path + @"\XMLCopy.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel12,"","",true,"", Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,"","","","");
        }
        private void CheckExcellProcesses()
        {
            Process[] AllProcesses = Process.GetProcessesByName("excel");
            myHashtable = new Hashtable();
            int iCount = 0;
            foreach (Process ExcelProcess in AllProcesses)
            {
                myHashtable.Add(ExcelProcess.Id, iCount);
                iCount = iCount + 1;
            }
        }
        private void KillExcel()
        {
            Process[] AllProcesses = Process.GetProcessesByName("excel");
            // check to kill the right process
            foreach (Process ExcelProcess in AllProcesses)
            {
                if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
                    ExcelProcess.Kill();
            }
            AllProcesses = null;
        }
        private void btnBrowse2_Click(object sender, EventArgs e)
        {
            DialogResult resDialog = openFileDialog2.ShowDialog();
            if (resDialog.ToString() == "OK")
            {
                textBox2.Text = openFileDialog2.FileName;
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_isDirty)
            {
                if (DialogResult.Yes != MessageBox.Show(
                    "Close the application?",
                    "Warning!!!!",
                     MessageBoxButtons.YesNo,
                     MessageBoxIcon.Warning,
                     MessageBoxDefaultButton.Button2))
                {
                    e.Cancel = true;
                }
            }
        }
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //backgroundWorker1.ReportProgress(10);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(20);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(30);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(40);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(50);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(70);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(95);
            //Thread.Sleep(164);
            //backgroundWorker1.ReportProgress(100);
            CountTheTime();
        }
        private void CountTheTime()
        {
            int initialValue = 100;
            for (int count = 0; count < initialValue; count = count + 2)
             {
                 Thread.Sleep(100);
                 backgroundWorker1.ReportProgress(count);
             }
        }
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ExcelCompare();
            textBox1.Text = "";
            textBox2.Text = "";
            btnCompare.Enabled = true;
            btnCompare.BackColor = Color.LightSkyBlue;
            btnCompare.ForeColor = Color.Black;
            toolStripProgressBar1.Value = 0;
            toolStripProgressBar1.Visible = false;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripProgressBar1.Visible = false;
        }


    }
}



请帮忙!!!!



Please help!!!!

推荐答案

public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    MethodInvoker involker = delegate
    {
        tooltipProgressBar1.Value = e.ProgressPercentage;
    };
    tooltipProgressBar1.BeginInvoke(invoker);
}



您也确实不需要发布所有theat源代码.它只是使您的问题变得混乱.



You really didn''t need to post all theat source code, either. It just cluttered your question.




这篇关于后台工作者和Progressbar无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 16:54