我工作的一個項目,我需要在Excel中一些工作流程自動化和我打了一個非常討厭的障礙。在該項目中,我使用Visual Studio Tools For Office創建文檔級加載項。用戶使用作爲該項目一部分的功能區控件來自動複製項目外部工作簿中的工作表。外部工作簿從SQL blob加載並寫入磁盤。外接程序代碼打開每個工作簿,將工作表複製到加載項工作簿中,然後關閉該外部工作簿。通常,第一個工作簿可以正常工作,但打開後續工作簿將引發AccessViolationException。AccessViolationException在ThisWorkbook.Application.Workbooks.Open
public void AddSheetFromTempFile(string tempfilePath)
{
Sheets sheets = null;
Excel.Workbook workbook = null;
Excel.Workbooks books = null;
try
{
books = this.Application.Workbooks;
//Throws AccessViolationException
workbook = books.Open(tempfilePath, 0, true, 5,
String.Empty, String.Empty, true, XlPlatform.xlWindows,
String.Empty, true, false, 0, true, true, false);
sheets = workbook.Worksheets;
sheets.Copy(After: this.GetLastWorksheet());
workbook.Close(SaveChanges: false);
}
finally
{
if (sheets != null)
{
Marshal.FinalReleaseComObject(sheets);
}
if (workbook != null)
{
Marshal.FinalReleaseComObject(workbook);
}
if (books != null)
{
Marshal.FinalReleaseComObject(books);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
//extension method for getting last worksheet
public static Microsoft.Office.Interop.Excel.Worksheet
GetLastWorksheet(this Microsoft.Office.Tools.Excel.WorkbookBase workbook)
{
int veryHiddenSheets = 0;
foreach(Worksheet sheet in workbook.Worksheets)
{
if(sheet.Visible == XlSheetVisibility.xlSheetVeryHidden)
{
veryHiddenSheets++;
}
}
int lastIndex = workbook.Worksheets.Count - veryHiddenSheets;
return workbook.Worksheets[lastIndex];
}
所以我已經將問題縮小到一組可重複的步驟。此問題似乎源於您向工作簿中添加N張圖紙,然後刪除它們並重新添加圖紙的情況。我啓用了本地調試,在此建議http://social.msdn.microsoft.com/forums/en-US/vsto/thread/48cd3e88-d3a6-4943-b272-6d7ea81e11e3。當上面的異常出現時,我會看到下面的調用堆棧。
[email protected]() + 0x15 bytes
[email protected]() + 0x15 bytes
[email protected]() + 0x43 bytes
[External Code]
First-chance exception at 0x2ff2489e in Excel.exe: 0xC0000005: Access violation reading location 0x00000000.
A first chance exception of type 'System.AccessViolationException' occurred in PublicCompModel.DLL
An exception of type 'System.AccessViolationException' occurred in PublicCompModel.DLL but was not handled in user code
不知道如果我濫用COM對象,但我肯定覺得很奇怪,我可以刪除所有表的複製本,並認爲這是本地到Excel。
請將您的答案標記爲答案。 – Artemix