程序很慢,为什么? 在C#中

我正在使用这段代码导出一个Excel的Wuth 256行(以后我需要256K行),但程序是非常慢比较Java,我读了一个文件夹中的所有文本文件,然后我读了所有在每个文件中,我寻找一个字母,如果我看到它,我将该行添加到Excel文件

我的程序有什么问题?

private void Create_Excel_File_Click(object sender, EventArgs e) { ProgressBarTimer.Start(); String[] Coulmn_Head = {"סוג פעולה"," נקלט בשעה"}; int Coulmn = 1, Row = 1; Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); for (Coulmn=1; Coulmn <=Coulmn_Head.Length; Coulmn++) { xlWorkSheet.Cells[Row, Coulmn] = Coulmn_Head[Coulmn - 1]; xlWorkSheet.Columns[Coulmn].AutoFit(); } Coulmn = 1; Row++; int CountErrors = 0; string[] Files = System.IO.Directory.GetFiles(SourceFolderText.Text, "*.txt"); for (int i = 0; i < Files.Length; i++) { string line; System.IO.StreamReader File_Now = new System.IO.StreamReader(Files[i]); while ((line = File_Now.ReadLine()) != null) { for (int j = 0; j < line.Length; j++) { if (line[j] >= 'א' && line[j] <= 'ת') { string[] words = line.Split('|'); foreach (string word in words) { xlWorkSheet.Cells[Row, Coulmn++] = word; } Coulmn = 1; Row++; j = line.Length; CountErrors++; } } } File_Now.Close(); } xlWorkBook.SaveAs(TargetFolderText.Text + "\\" + TargetFIleText.Text + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); MessageBox.Show(CountErrors + " Errors Found"); } 

Excel应用程序需要大量的时间进行初始化,并且每次触发处理程序时都会实例化它( Create_Excel_File_Click )。

所以你最好创build一个全局的应用程序范围的Excel实例,所以主机应用程序在启动时只会冻结一次。

 public class ExcelComponent { private static Excel.Application _app; public static App { get { if (_app == null) _app = new Excel.Application(); return _app; } } } private void Create_Excel_File_Click(object sender, EventArgs e) { Excel.Application xlApp = ExcelComponent.App; Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue); // etc. }