0

我正在编写一个使用 COM 互操作从 Excel 电子表格中提取图像的应用程序。

如果我将文件保存为 Excel 2010 中的 XLS(2003 格式),它工作得非常好,但是如果我将其保存为 XLSX(2007 到 2010 格式),它会产生此异常“服务器抛出异常。(来自 HRESULT 的异常:0x80010105 (RPC_E_SERVERFAULT))"

我的代码如下。pic.Copy(); 行抛出异常。与 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();
    }

任何想法为什么会发生这种情况?我的项目需要能够支持 2003 年和 2007/2010 年。

谢谢

4

1 回答 1

1

虽然您的目标是 Excel 2003 和 2007/更高版本,但我建议使用 OpenXml SDK 为 Excel 2007 及更高版本提取图片。首先,这是 SDK 比互操作更好的地方。我还没有为 Excel 做这件事,但为 PowerPoint 编写了代码来做同样的事情。它的速度非常快,因为您甚至不启动 Excel,而是直接使用 XML Excel 文件。其次,您似乎是在服务器上执行此操作,强烈建议避免使用 Interop。

于 2012-05-23T06:01:33.433 回答