不能被embedded。 使用适用的接口,而不是

我想添加一张照片到Excel Spread工作表,但不断收到以下错误?

错误1 Interoptypes“Microsoft.Office.Interop.Excel.ApplicationClass”不能被embedded。 改用适用的界面。

ApplicationClass(); 在下面的代码行中用红色标出下划线:

xlApp = new Excel.ApplicationClass();

可能有人请给我打电话,我该如何解决这个问题?

using Excel = Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; private void btnWriteSpreedSheet_Click(object sender, EventArgs e) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.ApplicationClass(); //This is where the problem is?????? xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //add some text xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com"; xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File"; xlWorkSheet.Shapes.AddPicture("C:\\csharp-xl-picture.JPG", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45); xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlApp); releaseObject(xlWorkBook); releaseObject(xlWorkSheet); MessageBox.Show ("File created !"); } private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; MessageBox.Show("Unable to release the Object " + ex.ToString()); } finally { GC.Collect(); } } } 

在您的项目中,展开“参考”,findMicrosoft Office互操作参考。 右键单击它并select属性,并将“embeddedInteroptypes”更改为false

正如在MSDN博客文章中所解释的,您也可以更改而不是禁用“Embed Interop Types”

 xlApp = new Excel.ApplicationClass(); 

 xlApp = new Excel.Application(); 

虽然Excel.Application是一个接口,但是我们可以实例化它,因为它是用一个CoClass属性来装饰的,正如在其他SO回答中所解释的那样: https : //stackoverflow.com/a/11039870/501196

使用这种方法(Embed Interop Types = true)的优点是,您将需要在项目中部署较less的文件,而embedded的types只包含应用程序实际使用的方法和types。 当您使用外部互操作程序集时,您正在导入所引用的库公开的所有types和方法。

findMicrosoft.Office.Interop.Excel参考,并右键单击并更改“embeddedInteroptypes”状态falce,如果它是true。