2017-11-23 23 views
0

내 프로그램에서 여러 텍스트 파일을 선택하고 내용을 단일 텍스트 파일로 컴파일 한 다음 Excel 파일로 내보낼 수 있습니다. 진행 표시 줄을 사용하여 시도했지만 주요 루프가 완료된 후에 만 ​​업데이트됩니다. 루프가 완료되면 진행률 표시 줄이 최소값에서 최대 값으로 즉시 이동합니다. 그것은 생각처럼 천천히 증가하지 않습니다.DoWork 루프가 실행 중일 때 Backgroundworker가 ProgressBar를 업데이트하지 않음

public partial class Form1 : Form 
{ 
    List<string> path = new List<string>(); 
    Workbook excelworkbook = new Workbook(); 
    Worksheet excelworksheet = new Worksheet("First sheet"); 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void addfiles_Click(object sender, EventArgs e) 
    { 
     DialogResult dr = this.selectFiles.ShowDialog(); 
     path.Clear(); 
     if (dr == System.Windows.Forms.DialogResult.OK) 
     { 
      // Read the files 
      foreach (String file in selectFiles.FileNames) 
      { 
       try 
       { 
        path.Add(file); 
       } 
       catch (Exception ex) 
       { 
        MessageBox.Show(ex.ToString()); 
       } 
      } 
      numFiles.Text = path.Count.ToString(); 
     } 
    } 

    private void export_Click(object sender, EventArgs e) 
    { 
     export.Text = "Exporting..."; 
     export.Enabled = false; 
     addfiles.Enabled = false; 
     backgroundWorker1.RunWorkerAsync(); 
    } 

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
     try 
     { 
      backgroundWorker1.ReportProgress(15); //15% on progress bar 
      string[] readText = File.ReadAllLines(path[0]); 
      string[] readText_secondary; 
      string filename; 
      int real_length = readText.Length - 3; //create a text file that stores contents temporarily from multiple textfiles first..later will export into an excel file 
      using (StreamWriter streamWriter = new StreamWriter(string.Concat(Directory.GetCurrentDirectory(), "\\Temp_textfile.txt"), false)) //create temp text file 

      { 
       for (int i = 12; i <= real_length; i++) 
       { 
        backgroundWorker1.ReportProgress(((i/real_length) * 75) + 15); //suppose to update the UI here 
        streamWriter.Write(string.Concat(readText[i].Substring(4, 42))); //initial columns 
        streamWriter.Write(string.Concat(readText[i].Substring(59, 13))); //upperlimit column 
        if (i != 12) 
        { 
         streamWriter.Write(string.Concat(readText[i].Substring(46, 13))); //results column 
        } 
        else if (i == 12) 
        { 
         filename = Path.GetFileNameWithoutExtension(path[0]); //serial number column 
         streamWriter.Write(string.Concat(filename + " ")); 
        } 
        for (int x = 1; x < path.Count; x++) 
        { 
         readText_secondary = File.ReadAllLines(path[x]); //secondary files 
         if (x != (path.Count - 1)) 
         { 
          if (i != 12) 
          { 
           streamWriter.Write(string.Concat(readText_secondary[i].Substring(46, 13))); //write results 
          } 
          else if (i == 12) 
          { 
           filename = Path.GetFileNameWithoutExtension(path[x]); //write serial number header 
           streamWriter.Write(string.Concat(filename + " ")); 
          } 
         } 
         else 
         { 
          if (i != 12) 
          { 
           streamWriter.WriteLine(string.Concat(readText_secondary[i].Substring(46, 13))); //write results for last column 
          } 
          else if (i == 12) 
          { 
           filename = Path.GetFileNameWithoutExtension(path[x]); //write serial number header for last column 
           streamWriter.WriteLine(string.Concat(filename + " ")); 
          } 
         } 
        } 
       } 
      } 
      var lines = File.ReadAllLines(string.Concat(Directory.GetCurrentDirectory(), "\\Temp_textfile.txt")); 
      var rowcounter = 0; 
      foreach (var line in lines) 
      { 
       var columncounter = 0; 
       backgroundWorker1.ReportProgress(90); 
       string[] values = new string[200]; //extract the initial columns 
       values[0] = line.Substring(0, 10); values[1] = line.Substring(11, 8); values[2] = line.Substring(20, 8); values[3] = line.Substring(29, 12); values[4] = line.Substring(42, 12); 
       for (int y = 0; y < path.Count; y++) 
       { 
        values[5 + y] = line.Substring((55 + (13 * y)), 13); //extract results column 
       } 
       foreach (var value in values) 
       { 
        excelworksheet.Cells[rowcounter, columncounter] = new Cell(value); //write column by column 
        columncounter++; 
       } 
       rowcounter++; 
      } 
      excelworkbook.Worksheets.Add(excelworksheet); //create the excel file from object 
      string timedate = DateTime.Now.ToString("dd-MM-yyyy"); 
      string excel_name = "\\ExportedData_" + timedate; 
      int counter = 1; 
      string new_path = string.Concat(Directory.GetCurrentDirectory() + excel_name + ".xls"); //this part is to prevent overwriting 
      while (File.Exists(new_path)) 
      { 
       new_path = string.Concat(Directory.GetCurrentDirectory() + excel_name + "(" + counter + ")" + ".xls"); 
       counter++; 
      } 
      excelworkbook.Save(new_path); //save into path 

      if (File.Exists(string.Concat(Directory.GetCurrentDirectory(), "\\Temp_textfile.txt"))) //delete temporary text file 
      { 
       File.Delete(string.Concat(Directory.GetCurrentDirectory(), "\\Temp_textfile.txt")); 
      } 
      backgroundWorker1.ReportProgress(100); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error occurred!\n" + ex, "Error Window", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      addfiles.Text = "Add Files"; 
      export.Text = "Export!"; 
      numFiles.Clear(); 
      addfiles.Enabled = true; 
      export.Enabled = true; 
     } 
    } 

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     progressBar1.Value = e.ProgressPercentage; 
    } 

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 
     MessageBox.Show("Done exporting!", "Notification Window", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); 
     addfiles.Text = "Add Files"; 
     export.Text = "Export!"; 
     numFiles.Clear(); 
     addfiles.Enabled = true; 
     export.Enabled = true; 
    } 
} 

내가 여기에 문제가 무엇에 보이는 캔트 : 여기 내 코드입니다. 누군가가 올바른 방향으로 나를 가리킬 수 있습니까?

답변

0
backgroundWorker1.ReportProgress(((i/real_length) * 75) + 15); 

문제는 (i/real_length) 0을 반환하면 integer division을 사용하고 있기 때문에 것입니다.

backgroundWorker1.ReportProgress((int)((((double)i/real_length) * 75) + 15)); 

또는 :

대신 당신은 할 필요가

backgroundWorker1.ReportProgress(i * 75/real_length + 15); 

나는 전자를 추천 할 것입니다.

+0

정수 나누기가 정수 결과로 나타나는 경우 보고서 진행률에서 해당 값을 읽을 수 없습니까? 우리가 결과를 double로 선언하고 다시 integer로 변환 할 필요가있는 이상한 것처럼 보입니다 ... 미숙하게 보일 경우 미안 해요. 저는 진정으로 혼란 스럽습니다. – user107257

+0

하지만 int i = for 루프에서 12. 어떻게 아직도 i/real_length가 0이 될까요? – user107257

+0

omg, 이제 알겠지만 컴파일러는 정수형 인 경우 0.9667을 0으로 자릅니다. 고맙습니다! – user107257