C# - Word 互操作获取 Excel table(Excel 工作表)

C# - Word interop get Excel table(Excel worksheet)

找了一整天我还是找不到如何访问word文件中的工作表。

我正在使用此代码打开文件:

Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
appWord.Visible = false;

wordDocument = appWord.Documents.Open(General.GetInvoicePath(invoices[currentItem.Index]).Replace('/', '\'));

现在您可以使用 wordDocument.Tables 访问所有 table 但不能访问 EXCEL table.

这是我试图在 c#

中获得的那种 object/table

我用了很多方法尝试找到它:

Console.WriteLine("TEST :" + wordDocument.Content.Tables.Count);
Console.WriteLine("TEST :" + wordDocument.Content.SmartTags.Count);
Console.WriteLine("TEST :" + wordDocument.Content.Frames.Count);
Console.WriteLine("TEST :" + wordDocument.Content.XMLNodes.Count);
Console.WriteLine("TEST :" + wordDocument.XMLNodes.Count);
Console.WriteLine("TEST :" + wordDocument.Tables.Count);
Console.WriteLine("TEST :" + wordDocument.TablesOfContents.Count);
Console.WriteLine("TEST :" + wordDocument.TablesOfAuthorities.Count);
Console.WriteLine("TEST :" + wordDocument.TablesOfFigures.Count);
Console.WriteLine("TEST :" + wordDocument.Subdocuments.Count);
Console.WriteLine("TEST :" + wordDocument.Content.Subdocuments.Count);

word文档中的exceltable是OLE嵌入对象,不是原生word元素。您当然可以枚举、添加或删除此类对象,但我不确定是否可以进行任何交互。它们是 InlineShapeshttps://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.wdinlineshapetype?view=word-pia 查看枚举中嵌入的内联 OLE 对象。

InlineShape embeddedWorkbook = wordDocument.InlineShapes[1];
embeddedWorkbook.OLEFormat.Activate();
Workbook workbook = (Workbook)embeddedWorkbook.OLEFormat.Object;

var cellValue = (string)(workbook.Sheets[1].Cells[6, 17] as Microsoft.Office.Interop.Excel.Range).Value;

Console.WriteLine(cellValue);

这是访问工作表并获取单元格值的最终解决方案。