我现在使用此代码导出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");
}
答案 0 :(得分:2)
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.
}