Extracting images from Excel 2007 - 2010 document

0

I am writing an application that extracts images from an Excel spreadsheet using COM interop.

It works perfectly fine if I save the file as an XLS (2003 format) from Excel 2010 however if I save it as an XLSX (2007 to 2010 format) it produces this exception "The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))"

My code is below. The exception is thrown by the line pic.Copy(); which works perfectly fine with an XLS.

    public static BitmapSource[] ImportImages(string FileName)
    {
        //Create the Excel Object
        ExcelObj = new Microsoft.Office.Interop.Excel.Application();

        //Create the Workbooks wrapper
        Workbooks workbooks = ExcelObj.Workbooks;

        //Open the Excel workbook
        Workbook workbook = workbooks.Open(FileName);

        //Reference the worksheets in the Excel file
        Sheets sheets = workbook.Worksheets;

        List<BitmapSource> images = new List<BitmapSource>();

        List<Picture> pics = new List<Picture>();

        //Reference the first sheet in the workbook
        Worksheet sheet = sheets[1];

        for (int i = 1; i < 30; i++)
        {
           pics.Add(sheet.Pictures(i));
        }

        foreach (Picture pic in pics)
        {
            pic.Copy();

            if (Clipboard.ContainsImage())
            {
                images.Add(Clipboard.GetImage());
            }

            Marshal.ReleaseComObject(pic);
        }

        Marshal.ReleaseComObject(sheet);
        Marshal.ReleaseComObject(workbooks);
        Marshal.ReleaseComObject(workbook);
        Marshal.ReleaseComObject(sheets);
        ExcelObj.Quit();
        Marshal.ReleaseComObject(ExcelObj);

        return images.ToArray();
    }

Any ideas why this is happening? I need to be able to support 2003 and 2007/2010 with my project.

Thanks

c#
.net
excel
com
interop
asked on Stack Overflow May 23, 2012 by Alex Wiese

1 Answer

1

While you are targeting both Excel 2003 and 2007/above, I would suggest using the OpenXml SDK to extract pictures for Excel 2007 and above. First off, this is something where the SDK works much better than interop. I haven't done it for Excel, but wrote code to do the same thing for PowerPoint. It's blazing fast because you don't even launch Excel, instead you are directly working of the XML Excel file. Second, it seems that you are doing this on a server, where it's highly advisable to avoid Interop.

answered on Stack Overflow May 23, 2012 by Mathias

User contributions licensed under CC BY-SA 3.0