2017-10-19 2 views
1

Ich habe eine Excel-Datei, von der ich eine Möglichkeit entwickelt, alle Inhalte in Blatt 1 zu lesen und füllt es in eine Listview, im Grunde hat das Blatt Daten in Zellen A-D. aber die Zahl ist 120.000. Wenn ich den Code ausführe, liest er diese Dateien, braucht Zeit, aber während des Prozesses, jede Aktion auf dem Formular wie das Minimieren oder Klicken auf das Formular irgendwo friert das Programm ein und bringt es zum Absturz. Wie kann ich die Leistung verbessern, wie es bei einem guten Programm der Fall ist? Hier ist mein Code unten.Optimierung des Speichers beim Lesen eines großen Excel-Blattes

private void button1_Click(object sender, EventArgs e) 
    { 
     Microsoft.Office.Interop.Excel.Application ExcelObj = new 
     Microsoft.Office.Interop.Excel.Application(); 
     OpenFileDialog openFileDialog1 = new OpenFileDialog(); 
     // prepare open file dialog to only search for excel files (had 
     // trouble setting this in design view) 

     openFileDialog1.FileName = "*.xlsx"; 
     if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      // Here is the call to Open a Workbook in Excel 
      // It uses most of the default values (except for the read-only 
      // which we set to true) 

       Workbook theWorkbook = 
       ExcelObj.Workbooks.Open(openFileDialog1.FileName, 0, true, 
       5,"", "", true, XlPlatform.xlWindows, "\t", false, false, 
       0, true); 


      // get the collection of sheets in the workbook 

       Sheets sheets = theWorkbook.Worksheets; 

      // get the first and only worksheet from the collection of 
      // worksheets 

      Worksheet worksheet = (Worksheet)sheets.get_Item(1); 

      // loop through 10 rows of the spreadsheet and place each row in 
      // the list view 

      for (int i = 1; i <= 10; i++) 
      { 
       Range range = worksheet.get_Range("A" + i.ToString(), "J" + 
       i.ToString()); 
       System.Array myvalues = (System.Array)range.Cells.Value; 
       string[] strArray = ConvertToStringArray(myvalues); 
       listView1.Items.Add(new ListViewItem(strArray)); 
      } 
     } 

    } 


     string[] ConvertToStringArray(System.Array values) 
      { 
     // create a new string array 

     string[] theArray = new string[values.Length]; 

     // loop through the 2-D System.Array and populate the 1-D String 
     // Array 

     for (int i = 1; i <= values.Length; i++) 
     { 
      if (values.GetValue(1, i) == null) 
       theArray[i - 1] = ""; 
      else 
       theArray[i - 1] = (string)values.GetValue(1, i).ToString(); 
     } 
     return theArray; 
    } 

Antwort

Verwandte Themen