程序很慢,为什么?在c#

本文关键字:为什么 程序 | 更新日期: 2023-09-27 17:50:19

我使用此代码导出excel与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");

    }

程序很慢,为什么?在c#

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

所以你最好创建一个全局应用范围的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.
}