【发布时间】:2018-03-25 06:11:58
【问题描述】:
使用此方法后我无法关闭 excel。我尝试使用在 StackOverflow 中找到的一些方法,但似乎无处可去。请你看看我做错了什么?谢谢!
public void readAllFromXLS()
{
Excel.Application refExcel = new Excel.Application();
Excel.Workbook refFile = refExcel.Workbooks.Open(Application.StartupPath + "\\Resources\\reference files\\price list.xlsx");
try
{
string workSheet;
if (Form1.sesion.isSRA)
workSheet = "SRA";
else
workSheet = "Standard";
Excel.Worksheet refSheet = refFile.Sheets[workSheet] as Excel.Worksheet;
for (int row = 2; row <= refSheet.UsedRange.Rows.Count; row++)
{
Some Cell Reading Here...
}
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(refSheet);
}
catch (Exception e)
{
DialogResult r = MessageBox.Show("Price List Excel File Error.", "File Read Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
Console.WriteLine("------");
Console.WriteLine(e);
}
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(refFile);
refExcel.Quit();
Marshal.FinalReleaseComObject(refExcel);
}
【问题讨论】:
-
你打电话给
refExcel.Quit()有什么原因之后GC.Collect? -
@MickyD,谢谢你的链接我已经看到了,我看不出我在做什么错了。
-
@mjwills 感谢您查看它,我只是在尝试不同的版本,看看它是否对我的情况有帮助。
-
如果您想使用
GC.Collect技术,那么您肯定需要调用refExcel.Quit()首先。然后,在调用readAllFromXLS做GC.Collect(); GC.WaitForPendingFinalizers();的函数中,重复3次。