如何处理 "no constructors defined" 和 "type cannot be embedded" 异常?

How can I deal with "no constructors defined" and "type cannot be embedded" exceptions?

添加 Excel 12 引用(其中添加了 Microsoft.Office.Interop.Excel 和 VBIDE DLL)后,我从 here 复制并粘贴了代码,即:

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

但是,它无法构建,有两个错误消息:

类型 'Microsoft.Office.Interop.Excel.ApplicationClass' 没有定义构造函数

-和:

互操作类型 'Microsoft.Office.Interop.Excel.ApplicationClass' 无法嵌入。请改用适用的界面。

...两者都指向这条线作为罪魁祸首:

xlApp = new Excel.ApplicationClass();

如果我从该行中删除 "new",第一个错误消息将更改为:

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

所以这是一种 "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)。