2012-05-23 38 views
0

我在写一个应用程序,它使用COM互操作从Excel电子表格中提取图像。从Excel 2007 - 2010中提取图像文档

如果我从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。

感谢

回答

1

当你同时指定Excel 2003和2007 /以上,我建议使用的OpenXML SDK中提取图片,Excel 2007和上方。首先,这是SDK工作比interop更好的地方。我还没有为Excel做过,但是编写了代码来为PowerPoint做同样的事情。它的速度非常快,因为您甚至不会启动Excel,而是直接使用XML Excel文件。其次,你似乎在服务器上这样做,避免Interop的强烈建议。

+0

是的,这似乎是这个问题的最佳解决方案。这将在工作站而不是服务器上运行。我将不得不使用XLSX文件的OpenXml SDK和XLS的原始代码。 –