Excel interop 缺少方法异常

6

在我的C#程序中,我正在使用Excel 2010互操作程序集。通过这个程序集,我可以读写Excel文件,并且在开发环境(包含Office 2010)中执行良好。但是在客户机上,即使他们也安装了Office 2010和Office PIA,他们仍会在调用WriteToExcel()方法时看到下面的异常。

Unhandled Exception: System.MissingMethodException: Method not found: 'System.Type System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(System.GUID)'.

以下是我的代码片段。
[STAThread]
static void Main(string[] args){

       // read user input, process and write data to Excel
       WriteToExcel();
 }

[STAThread]
static void WriteToExcel(){
     Application xlsApplication = new Application();
     Workbook xlsWorkbook = xlsApplication.Workbooks.Open(excelFilePath);
     // write data to excel
     // close up            
 }

你能在客户端机器上进行调试吗?另外,Furqan的答案有效吗? - JMK
1
在那台机器上安装.NET 4.5。 - Hans Passant
很好的观点,也许楼主在开发机器上安装了4.5,而目标是4.0(在客户机器上),这可能是一个bug,因为4.5替换了4.0编译器,从而掩盖了4.0中的错误。 - JMK
感谢@JMK的提示。将.NET版本降至4.0后,问题已解决。 - Mahender
2个回答

5
降低 .net 版本到 4.0 后问题得以解决。之前我的开发机器上装了 4.5 版本,应用程序也是用这个版本编译的。客户端机器上只有 4.0 版本,降低 .net 版本后问题得以解决。

1
这对每个人都很明显,除了我,但只需在VS中的应用程序属性页面上降低“目标框架”设置即可。最初,我认为需要在我的开发环境中卸载4.5并安装4.0。 - aland
感谢您发布这个答案。我遇到了相同的目标框架问题,直到阅读了您的帖子才意识到。 - EMR

0

尝试使用以下代码:

[STAThread]
static void WriteToExcel()
{
    Application xlsApplication = new Application();
    var missing = System.Type.Missing;
    Workbook xlsWorkbook = xlsApplication.Workbooks.Open(excelFilePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
    // write data to excel
    // close up            
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接