我试图打开一个xls文件,读入几行数据,从数据中形成一个自定义列表,然后关闭excel表。这就是我所拥有的:
InitializeWorkbook(Path);
List<Custom> list = new List<Custom>();
Worksheet wkSht = (Worksheet)workBk.Worksheets[3];
if (wkSht.Name.Equals("Sht3", StringComparison.OrdinalIgnoreCase))
{
Range PartNumRange = wkSht.get_Range("A:A", System.Reflection.Missing.Value);
Range RevRange = wkSht.get_Range("C:C", System.Reflection.Missing.Value);
Range SwRange = wkSht.get_Range("L:L", System.Reflection.Missing.Value);
Range NomenRange = wkSht.get_Range("M:M", System.Reflection.Missing.Value);
// Start at Row 6
int i = 6;
object Num = (PartNumRange[i, 1] as Range).Text;
object Nomen = (NomenRange[i, 1] as Range).Text;
object Sw = (SwRange[i, 1] as Range).Text;
object SwRev = (RevRange[i, 1] as Range).Text;
while (!string.IsNullOrEmpty(Num.ToString()) || !string.IsNullOrEmpty(Nomen.ToString()) || !string.IsNullOrEmpty(Sw.ToString()) || !string.IsNullOrEmpty(SwRev.ToString()))
{
if (!string.IsNullOrEmpty(Nomen.ToString()) && !string.IsNullOrEmpty(Sw.ToString()) && !string.IsNullOrEmpty(SwRev.ToString())
{
Custom item = new Custom();
item.PartNumber = (PartNumRange[i, 1] as Range).Text.ToString();
item.Nomenclature = (NomenRange[i, 1] as Range).Text.ToString();
item.SwNumber = (SwRange[i, 1] as Range).Text.ToString();
item.SwRevision = (RevRange[i, 1] as Range).Text.ToString();
list.Add(item);
}
i++;
Num = (PartNumRange[i, 1] as Range).Text;
Nomen = (NomenRange[i, 1] as Range).Text;
Sw = (SwRange[i, 1] as Range).Text;
SwRev = (RevRange[i, 1] as Range).Text;
}
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(PartNumRange);
Marshal.ReleaseComObject(RevRange);
Marshal.ReleaseComObject(SwRange);
Marshal.ReleaseComObject(NomenRange);
Marshal.ReleaseComObject(wkSht);
workBk.Close(false, System.Reflection.Missing.Value, false);
Marshal.ReleaseComObject(workBk);
Marshal.ReleaseComObject(ExcelWorkSheets);
ExcelApp.Quit();
Marshal.ReleaseComObject(ExcelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
}
我不知道为什么但是在完成执行后Excel没有关闭。只有当程序退出时才退出Excel。我尝试了各种各样的组合,避免了两点规则,但仍然没有。关于我缺少的任何想法?
编辑:调用ExcelApp.Quit将关闭ExcelApp和ExcelWorksheets。
答案 0 :(得分:1)
您可能想看一下这篇文章:How do I properly clean up Excel interop objects?
有很多关于在C#中处理COM对象的深入讨论,你可能会发现它们很有帮助。值得一读。
答案 1 :(得分:0)
你还需要在
上打电话调用Marshal.ReleaseComObject处理运行时可调用包装器,但让应用程序本身仍处于活动状态并且无法启动。
答案 2 :(得分:0)
您可以尝试使用此代码 - 它可以正常工作
while (Marshal.ReleaseComObject(YourRange) > 0)
{}
while (Marshal.ReleaseComObject(YourWorkSheet) > 0)
{}
while (Marshal.ReleaseComObject(YourWorkBook) > 0)
{}
YourApplication.quit()
while (Marshal.ReleaseComObject(YourApplication) > 0)
{}