【问题标题】:Extracting images from Excel 2007 - 2010 document从 Excel 2007 - 2010 文档中提取图像
【发布时间】:2012-05-23 04:48:27
【问题描述】:

我正在编写一个使用 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 年。

谢谢

【问题讨论】:

    标签: c# .net excel com interop


    【解决方案1】:

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

    【讨论】:

    • 是的,这似乎是解决这个问题的最佳方法。这将在工作站而不是服务器上运行。我将不得不使用 OpenXml SDK 处理 XLSX 文件和我的 XLS 原始代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多