After adding the Excel 12 reference (which added Microsoft.Office.Interop.Excel and VBIDE DLLs), I copy-and-pasted the code from here, namely this:
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
However, it fails to build with two err msgs:
The type 'Microsoft.Office.Interop.Excel.ApplicationClass' has no constructors defined
-and:
Interop type 'Microsoft.Office.Interop.Excel.ApplicationClass' cannot be embedded. Use the applicable interface instead.
...both of which point to this line as the culprit:
xlApp = new Excel.ApplicationClass();
If I remove "new" from that line, the first err msg changes to:
'Microsoft.Office.Interop.Excel.ApplicationClass' is a 'type', which is not valid in the given context
So it's a "Catch 2" situatiion - whichever I do, it catches two errors.
What can I do to remedy this?
Changing the code to this:
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();
. . .
...works (using Excel.Application instead of Excel.ApplicationClass).