【问题标题】:Use progress bar to read data from excel file using c#使用进度条使用c#从excel文件中读取数据
【发布时间】:2013-11-10 13:26:15
【问题描述】:

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

这就是我想做的-:

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

这就是我所做的-:

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

    // Start the BackgroundWorker.
            fileReadingbackgroundWorker.RunWorkerAsync();
    
  • 报告进度的 sn-p

    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;
    }
    

第二个sn-p中的fileReadingbackgroundWorker.ReportProgress(precentProgressFile);行抛出异常

我无法理解这里出了什么问题。 我正在使用 Visual Studio 12.0 和 .Net 4.0 有什么问题请追问

不与Accessing UI Control from BackgroundWorker Thread - C# 重复 原因是我没有在任何地方使用 DispatcherInvoke。

【问题讨论】:

  • 请添加异常信息。异常是给开发者的消息,到底出了什么问题。您的程序试图告诉您,但您(还)不听。
  • 不是从 BackgroundWorker 线程访问 UI 控件的副本 - C# 原因是我没有在任何地方使用 DispatcherInvoke。

标签: c# .net-4.0


【解决方案1】:

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

【讨论】:

  • 对不起,我忘了提,但我做到了
  • @vin 那么我真的需要至少异常的类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多