【发布时间】:2023-03-16 18:21:01
【问题描述】:
这是我的代码。请朋友们帮帮我。此代码可以将任何文本文档转换为 excel。但是在大型文档中,它需要很多时间。我该如何解决这个问题?
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
xlApp.ScreenUpdating=false;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
FileInfo theSourceFile = new FileInfo(@"" + file);
StreamReader reader = theSourceFile.OpenText();
int raw = 1; int column = 1;
String text = "";
do
{
text = reader.ReadLine();
if (text != null)
{
string[] ss = text.Split('|');
int index = 0; double result;
//WRITING DATA LINES
for (int i = 1; i < ss.Length; i++)
{
if (!ss[index].Contains('.')) //recognising strings by filtering currency values using "." sign (decimal point)
{
xlWorkSheet.Cells[raw, column] = ss[index];
index++; column++;
}
else if (double.TryParse(ss[index], out result))//writing and formating currency values
{ xlWorkSheet.Cells[raw, column] = String.Format("{0:n}", result);
index++; column++;
}
else
{
xlWorkSheet.Cells[raw, column] = ss[index];//writing "." containing non currcy values
index++; column++;
}
}
}
raw++; column = 1;
} while (text != null);
xlWorkSheet.Columns.AutoFit();
xlWorkBook.SaveAs(@"" + textBox6.Text + @"\" + line_dup + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
try
{
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
catch (Exception) { }
foreach (Process clsProcess in Process.GetProcesses())
if (clsProcess.ProcessName.Equals("EXCEL")) //KILLING EXCELL Process
clsProcess.Kill();
richTextBox1.Text += "\n" + line + "\t" + "excell file created";
MessageBox.Show("Excel files created , you can find the files in @" + textBox6.Text + line_dup + ".xls");
foreach (Process clsProcess in Process.GetProcesses())
if (clsProcess.ProcessName.Equals("EXCEL")) //KILLING EXCELL Process
clsProcess.Kill();
【问题讨论】:
-
这个属于Code Review
-
@bansi,请阅读Guide to Code Review for Stack Overflow users。特别是如果代码被破坏,它不适合代码审查。由于大括号似乎不匹配或存在一些非常奇怪的缩进问题,因此这段代码看起来很糟糕
-
@holroy 根据 OP,代码正在运行并需要优化。代码审查的完美候选人。
-
快速粘贴到 VS 中发现没有丢失大括号。只要代码起作用(OP 声称它确实如此),它就应该成为代码审查的主题
-
查看代码时,我看到 8 个左大括号和 12 个右大括号。要么我是盲人,要么这个代码被破坏了。