2015-10-27 51 views
0

添加了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 

但是,它未能建立具有兩個ERR的MSG:

類型 'Microsoft.Office.Interop.Excel.ApplicationClass' 沒有構造定義

-and:

Interop類型'Microsoft.Office.Interop.Excel.ApplicationClass'不能嵌入。改爲使用適用的界面。

...這兩個點,以這條線的罪魁禍首:

xlApp = new Excel.ApplicationClass(); 

如果我從該行刪除「新」,第一個錯誤消息的變化:

'微軟.Office.Interop.Excel.ApplicationClass'是'type',在給定的上下文中無效

所以這是一個「Catch 2」的情況 - 無論我做什麼,它都會捕獲兩個錯誤。

我該怎麼做才能解決這個問題?

+3

難道不只是'new Excel.Application()'? –

回答

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

相關問題