Search code examples
c#ms-wordoffice-interopembedded-resourceexcel-interop

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


I am trying to read an Excel sheet embedded in a Word document. What do I do after opening the Word document? These are the references I am using (Excel,Word)-- are there any others I need to use?

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??
}

Solution

  • In order to interact with the embedded worksheet, it's necessary to Activate it.

    Once it's activated, you can handle the Excel.Workbook, Excel.Application and Excel.Worksheet and Excel.Range objects:

        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"];
        }