Interop Word & Excel : Can't close an Excel workbook embedded in Word document

时光毁灭记忆、已成空白 提交于 2020-04-12 04:06:34

问题


I got an error when i'm closing the Excel workbook embedded in a Word document. This document got only one Excel chart. Nothing else : texts, etc...

This is the code :

Application _application = new Application
{
    Visible = false,
};
object oFilename = fileName;
object oFormat = WdOpenFormat.wdOpenFormatXMLDocument;
_document = _application.Documents.Open(
     ref oFilename, ref _missing, ref _faux, ref _missing, ref _missing, ref _missing,
     ref _missing, ref _missing, ref _missing, ref oFormat, ref _missing, ref _faux,
     ref _missing, ref _missing, ref _missing, ref _missing);

_document.Activate();

InlineShape shape1 = _document.InlineShapes[1];
Microsoft.Office.Interop.Word.Chart chart1 = shape1.Chart;
Workbook wb1 = chart1.ChartData.Workbook;
wb1.Application.WindowState = XlWindowState.xlMinimized;
Worksheet ws1 = wb1.Worksheets["Graphe"];
ws1.Cells[2, "A"].Value = 1000;

// --- THIS IS THE LINE WHICH HANDLE EXCEPTION
wb1.Close(Type.Missing, Type.Missing, Type.Missing);
// ---

_document.Close(ref _missing, ref _missing, ref _missing);
_application.Application.Quit(ref _missing, ref _missing, ref _missing);

Let's see the exception (seem to be useless..) : Exception de HRESULT : 0x800A03EC

Stack trace :

à Microsoft.Office.Interop.Excel._Workbook.Close(Object SaveChanges, Object Filename, Object RouteWorkbook)
à TestFile.Program.Main(String[] args) dans C:\[Users..]\MyProject\Program.cs :ligne 53

Thanks for your help, Regards


回答1:


I found a workaround...

Replace :

wb1.Close(Type.Missing, Type.Missing, Type.Missing);

With :

wb1 = null;

/!\ BUT be careful about the Dispose of wb1 because we are still talking about a COM object



来源:https://stackoverflow.com/questions/60788443/interop-word-excel-cant-close-an-excel-workbook-embedded-in-word-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!