0

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

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”,则第一个 err msg 将更改为:

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

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

我能做些什么来解决这个问题?

4

1 回答 1

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

于 2015-10-27T17:16:59.543 回答