我如何处理“没有构造函数定义”和“类型不能嵌入”异常?

时间:2015-10-27 17:13:41

标签: c# excel office-interop excel-interop ole-automation

添加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”类型没有定义构造函数

- 和

无法嵌入

Interop类型'Microsoft.Office.Interop.Excel.ApplicationClass'。请改用适用的界面。

......两者都指向这一行作为罪魁祸首:

xlApp = new Excel.ApplicationClass();

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

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

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

我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

将代码更改为:

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)。