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

C#-Word互操作获取Excel表格(Excel工作表),c#,winforms,ms-word,interop,C#,Winforms,Ms Word,Interop,搜索了一整天后,我仍然找不到如何访问word文件中的工作表 我正在使用以下代码打开文件: Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application(); appWord.Visible = false; wordDocument = appWord.Documents.Open(General.GetInvoicePath(invoices[currentI

搜索了一整天后,我仍然找不到如何访问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访问所有表,但不能访问EXCEL表

这就是我在c中尝试获取的对象/表#

我用了很多方法来寻找它:

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文档中的excel表是OLE嵌入对象,而不是本机word元素。您当然可以枚举、添加或删除此类对象,但我不确定是否可以进行任何交互。它们是
InlineShapes
:请参见枚举中嵌入的内联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);

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

通过“激活”对象并获取工作簿对象,“应该”可以与对象交互。看看这里:@blins谢谢,就是这样!