Search code examples
c#vstoepplusepplus-4

VSTO Excel Read from Current Open Workbook


Is it possible to read from an open Excel (xlsx) using EPPlus? I want the user to be able to open an Excel document, click the Add-In button and read data from the active worksheet. I don't need to write to the worksheet, only read from it.

Using interop I was able to get the full path to the open workbook but when I tried to actually access the workbook I got an I/O error. Any ideas how to get around this?

    var test = ( Microsoft.Office.Interop.Excel.Workbook ) Globals.ThisAddIn.Application.ActiveWorkbook;
    var test2 = test.ActiveSheet;
    //var test21 = ( Microsoft.Office.Interop.Excel.Workbook ) Globals.ThisAddIn.Application.ActiveSheet;
    var test3 = new FileInfo( test.FullName );


    using ( ExcelPackage package = new ExcelPackage( test3) ) // <--- I/O error here
    {
        var worksheet = package.Workbook.Worksheets[ "Sheet1" ]; 
        string myString = String.Format( "{0}", worksheet.Cells[ 1, 1 ].Text );
    }

Solution

  • Try non-exclusive access, like this:

    ....
    var stream = new FileStream(test.FullName, FileMode.Open, FileAccess.Read, 
                                FileShare.ReadWrite);  // <<< ---!!
    
    using (ExcelPackage package = new ExcelPackage(stream))
    {
       ...
    }