关闭Excel工作簿时出现COMException [英] COMException on closing Excel workbook
问题描述
我正在使用Excel = Microsoft.Office.Interop.Excel
将各种数据写入Excel工作表.
I'm using Excel = Microsoft.Office.Interop.Excel
to write various data to Excel sheets.
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;
try {
// Create new workbook
wb = (Excel.Workbook)(excelApp.Workbooks.Add(Type.Missing));
ws = wb.ActiveSheet as Excel.Worksheet;
// write data ...
// Save & Close
excelApp.DisplayAlerts = false; // Don't show file dialog for overwrite
wb.Close(true, targetFilename, Type.Missing);
} finally {
// Close the Excel process
if (null != ws)
Marshal.ReleaseComObject(ws);
if (null != wb)
Marshal.ReleaseComObject(wb);
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
GC.Collect();
}
此代码一次由多个线程执行,并且几乎一直在工作.甚至Excel进程也会在任务管理器中消失.
This code is exectued by multiple threads at a time, and it's been working almost always. Even the Excel processes disappear in task manager.
但是,有时会在wb.Close(true, targetFilename, Type.Missing)
处抛出System.Runtime.InteropServices.COMException
.它声称对目标文件名的访问被拒绝.尽管我一直在确保目标文件名是唯一的.
However, sometimes a System.Runtime.InteropServices.COMException
is thrown at wb.Close(true, targetFilename, Type.Missing)
. It claims that access on the target filename was denied. Though I've been making sure that the target filenames are unique.
异常可能是由于对Excel的任何错误处理还是我正在使用线程?
May the exception be due to any bad handling of Excel or maybe that I'm using threads?
推荐答案
显然,targetFilename并不是唯一的.大写/小写拼写有一个区别,似乎两个线程试图一次写入同一文件.使用targetFilename.ToLower()
可以轻松解决该问题.
Apparently, targetFilename wasn't really unique. There was one single difference in upper/lower case spelling, and it seems like two threads tried to write to the same file at once. The issue was easily solvable by using targetFilename.ToLower()
.
无论如何,如果您发现任何进一步的潜在问题,请发表评论.
Anyway, if you discover any further potential issues, please leave a comment.
这篇关于关闭Excel工作簿时出现COMException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!