我该如何处理“没有构造函数定义”和“types不能embedded”例外?

添加Excel 12参考(添加了Microsoft.Office.Interop.Excel和VBIDE DLLs)后,我从这里复制并粘贴代码,即:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsFormsAppExcelTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void buttonCreateExcelFile_Click(object sender, EventArgs e) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com"; xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls"); } private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; MessageBox.Show("Exception Occured while releasing object " + ex.ToString()); } finally { GC.Collect(); } } } // class } // namespace 

但是,它无法与两个错误消息构build:

types“Microsoft.Office.Interop.Excel.ApplicationClass”没有定义的构造函数

-和:

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

两者都指出这条线是罪魁祸首:

 xlApp = new Excel.ApplicationClass(); 

如果我从该行删除“新”,则第一个错误信息将更改为:

Microsoft.Office.Interop.Excel.ApplicationClass”是一个“types”,在给定的上下文中无效

所以这是一个“Catch 2”的情况 – 无论我做什么,它都会遇到两个错误。

我能做些什么来补救呢?

将代码更改为:

 private void buttonCreateExcelFile_Click(object sender, EventArgs e) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); . . . 

…工作(使用Excel.Application而不是Excel.ApplicationClass)。