我的脚本读取Excel表并获取一个范围,该范围包含不同媒体文件的名称,我将其添加到一个大列表中。我使用列表中的名称来搜索目录,如果它们存在于给定的文件目录中,那么它们将被添加到“existsAlready”列表中。如果它们不存在于给定文件中,则位于copyFiles目录中,然后将它们复制到给定目录并添加到“existsAdded”列表中。如果在任一目录中找不到它们,则将这些文件添加到“existsNegative”列表中。所有3个列表被打印到单独的列表框。如何让这个脚本读取一个excel,然后找到并复制文件运行得更快?
这一切工作,但我发现它运行有点慢:
1)虽然Excel的应用程序是不可见的,但它仍然推出了一秒钟,然后关闭,减速过程。
2)如果文件夹中存在所有文件或者文件需要复制,应用运行良好/快速,但是如果目录中找不到许多文件且无法复制,则运行速度很慢,如何我可以做得更快吗?我想这与它必须搜索整个目录并且找不到任何东西有关。
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open("@Excelfile");
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)excelWorkbook.Sheets[1];
excelApp.Visible = false;
excelApp.ScreenUpdating = false;
excelApp.DisplayAlerts = false;
Excel.Range range = xlWorkSheet.get_Range(B1:G1);
List<string> listFBX = new List<string>();
foreach (Excel.Range s in range)
{
listFiles.Add(s.Text());
}
List<string> existsAlready = new List<string>();
List<string> existsAdded = new List<string>();
List<string> existsNegative = new List<string>();
foreach (var item in listFiles)
{
string curFile = "X:\\Private\\DATA\\PROJECT DATA\\Database\\" + item;
string copyFrom = "X:\\Private\\DATA\\PROJECT DATA\\FilesToSearch" + item;
if (File.Exists(curFile))
{
existsAlready.Add(item);
}
else if (!File.Exists(curFile) && File.Exists(copyFrom))
{
File.Copy(copyFrom, curFile, true);
existsAdded.Add(item);
}
else
{
existsNegative.Add(item);
}
}
for (int i = 0; i < existsAlready.Count; i++)
{
listBox1.Items.Add(existsAlready.ElementAt(i));
}
for (int i = 0; i < existsAdded.Count; i++)
{
listBox2.Items.Add(existsAdded.ElementAt(i));
}
for (int i = 0; i < existsNegative.Count; i++)
{
listBox3.Items.Add(existsNegative.ElementAt(i));
}
为什么你甚至需要Excel互操作呢?为什么不使用能够本机读取Excel文件的库,如EPPlus,NPOI。 ClosedXML,Office XML SDK,Aspose等 – mason
如果Excel Interop占用了大部分时间,并且您正在阅读xlsx文件,那么您几乎可以肯定使用EPPlus或ClosedXml等库(https:// github的.com/ClosedXML/ClosedXML) – CalC