2

我在使用进度条时遇到问题,而他的应用程序从 Excel 表中读取和获取数据

这就是我想做的-:

  • 我的应用程序从工作簿中各种 Excel 工作表的单元格中读取数据
  • 读取数据后,会向用户显示一个消息框,显示“文件读取成功”
  • 我需要在从文件中读取数据时在表单中运行一个进度条,并且它需要在弹出消息框之前显示一次完成百分比

这就是我所做的-:

  • 我添加了一个后台工作者和一个进度条
  • 这是调用 Run worker 的代码片段,当单击按钮并选择要读取的文件时调用 RunWorkerAsync。

    // Start the BackgroundWorker.
            fileReadingbackgroundWorker.RunWorkerAsync();
    
  • 报告进度的片段

    int percentProcessFile =1;
    for (int i = 1; i <= countSheets; i++)
    {
        readSheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(i);
    
        for (int row = 2; row <= 100; row++)
        {
            if (readSheet.Cells[1][row].Text.ToString() != "")
            {
                for (int column = 1; column <= 15; column++)
                {
                    String Key = readSheet.Cells[1][row].Text.ToString();
                    String readCaptionCell = readSheet.Cells[column][1].Text.ToString();
                    String readCurrentCell = readSheet.Cells[column][row].Text.ToString();
                    if (readSheet.Name == "ISMB")
                          ISMBSections.Add(Key, readCaptionCell, readCurrentCell);
                    else if (readSheet.Name == "ISMC")
                          ISMCSections.Add(Key, readCaptionCell, readCurrentCell);
                 }                        
           }
           else
           {
               break;
           }
           precentProgressFile++;
           fileReadingbackgroundWorker.ReportProgress(precentProgressFile);
       }   
    }
    

该行fileReadingbackgroundWorker.ReportProgress(precentProgressFile);引发异常

  • 我也添加了以下几行

    private void fileReadingbackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int i = 1; i <= 100; i++)
        {
            // Wait 100 milliseconds.
            Thread.Sleep(100);
            // Report progress.
            fileReadingbackgroundWorker.ReportProgress(j);
    
        }
    }
    
    private void fileReadingbackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        fileReadingProgressBar.Value = e.ProgressPercentage;
    }
    

第二个片段中的行fileReadingbackgroundWorker.ReportProgress(precentProgressFile);引发异常

我无法理解这里出了什么问题。我正在使用 Visual Studio 12.0 和 .Net 4.0 请询问您是否有任何问题

不是从 BackgroundWorker 线程访问 UI 控件的副本- C# 原因是我没有在任何地方使用 DispatcherInvoke。

4

1 回答 1

0

BackgroundWorker 有一个名为的属性WorkerReportsProgress,需要将其设置为 true 才能报告进度。

于 2013-11-10T13:29:03.983 回答