如何使用 Interop 和 C# 读取嵌入在 Word 文档中的 Excel?

How do I read Excel embedded in a Word document using Interop with C#?

我正在尝试阅读嵌入在 Word 文档中的 Excel sheet。打开Word文档后怎么办?这些是我正在使用的参考资料 (Excel,Word)-- 我还需要使用其他参考资料吗?

using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;

Word.Application wordApp;
Word.Document wordDoc;
Word.Range wordRange;

public TestCase Test()
{
   wordApp = new Word.Application();
   wordDoc = wordApp.Documents.Open(@"document");

   what next??
}

嵌入文档在文档中以内联形状表示,因此您可以通过以下方式访问它们:

Sub Extract()
    Dim num as Integer
    Dim AD as document
    Set AD = activedocument

    Dim numObjects As Integer
    numObjects = AD.InlineShapes.count

    MsgBox numObjects  ' prints "11"

    For num = 1 To numObjects    
        If AD.InlineShapes(num).Type = 1 Then
            'it's an embedded OLE type so open it.            
            AD.InlineShapes(num).OLEFormat.Open
        End If
    Next num
End Sub

为了与嵌入式工作表交互,有必要Activate它。

一旦激活,您就可以处理Excel.WorkbookExcel.ApplicationExcel.WorksheetExcel.Range对象:

    static void Main()
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range xlRange;

        Word.Application wordApp = new Word.Application();
        wordApp.Visible = true;
        Word.Document wordDoc = wordApp.Documents.Open(@"c:\debug\word-excel.docm");

        // activate the object before you can interact with it
        wordDoc.InlineShapes[1].OLEFormat.Activate();

        xlWorkBook = wordDoc.InlineShapes[1].OLEFormat.Object;
        xlApp = xlWorkBook.Parent;
        xlWorkSheet = xlWorkBook.Worksheets[1];
        xlRange = xlWorkSheet.Range["A1:D10"];
    }