【发布时间】:2016-05-26 12:09:16
【问题描述】:
所以我有以下代码。如果我注释掉该行,它应该可以正常工作,但是一旦我取消注释该行 Excel 将无法正常关闭。
我不确定接下来要尝试什么。我远离 2 点问题,并试图坚持 1 点。但现在我不确定现在该怎么办。
代码中的 dt 是我正在填充的 DataTable。
Excel.Application app = null;
Excel.Workbooks books = null;
Excel.Workbook book = null;
Excel.Sheets sheets = null;
Excel.Worksheet sheet = null;
Excel.Range range = null;
try
{
app = new Excel.Application();
books = app.Workbooks;
book = books.Open(FilePath);
sheets = book.Sheets;
sheet = book.ActiveSheet;
int rcount = 45;
UpdateProgressBarMaxMethod(pbAssets, rcount);
int i = 0;
for (; i < rcount; i++)
{
//Comment out the below line and it works fine
dt.Rows.Add(sheet.Cells[i + 1, 1].Value,
sheet.Cells[i + 1, 2].Value,
sheet.Cells[i + 1, 3].Value,
sheet.Cells[i + 1, 4].Value,
sheet.Cells[i + 1, 5].Value,
sheet.Cells[i + 1, 6].Value,
sheet.Cells[i + 1, 7].Value,
sheet.Cells[i + 1, 8].Value,
sheet.Cells[i + 1, 9].Value);
UpdateProgressBarMethod(pbAssets, i);
}
UpdateProgressBarMethod(pbAssets, 0);
book.Close();
app.Quit();
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
finally
{
if (range != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
if (sheet != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
if (sheets != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
if (book != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
if (books != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
if (app != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
}
【问题讨论】:
-
对不起,我会解释更多。 DT 是一个数据表
-
我假设您已正确初始化数据表。然后,是单元格的内容(至少其中一个)与数据表列类型的类型不匹配。
-
是不是因为您在
sheet.Cells[i + 1, 2].Value上使用了“2 个点”,因此没有清理对sheet.Cells[i + 1, 2]返回的Range的引用? -
是的,我已初始化 DataTable 并正常工作。运行此代码时唯一无法正常工作的部分是关闭 excel。但如果我评论那条线。 Excel 可以正常运行和关闭。
-
@petelids 我什至没有想到这一点。但不确定需要做什么清理......因为我仍然在释放对象。还剩下什么?