Create and Excel File from C# Code

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I am fairly new to .NET progaramming and I am trying to write an Excel file from my C# program. I found some references online and decided to try the code in a separate file first, which worked.
I then tried using the code in conjunction with a saveDialogBox (in my full program) to create a full save path to write the file path to any directory. In my program, using the exact same code, I am now receiving these error messages:
System.Windows.Forms.Button does not contain a definition for XlFileFormat and no extension method XlFileFormat accepting a first argument of type System.Windows.Forms.Button could be found (are you missing a using directive or an assembly reference?)
System.Windows.Forms.Button does not contain a definition for XlSaveAsAccessMode and no extension method XlSaveAsAccessMode accepting a first argument of type System.Windows.Forms.Button could be found (are you missing a using directive or an assembly
reference?)
I have checked and re-checked the references to ensure that the Excel COM Reference is included. Ive also copied and compared both files to see if there is a difference between the code snippets and I cant see any.
Any help is appreciated.
The code I am using is as follows:
<span style="font-family:Consolas; color:#0000ff; font-size:x-small <span style="font-family:Consolas; color:#0000ff; font-size:x-small <span style="font-family:Consolas; color:#0000ff; font-size:x-small <span style="font-family:Consolas; color:#0000ff; font-size:x-small


<pre>using Excel = Microsoft.Office.Interop.Excel;

private void WriteToExcel(string name)
{

Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "It Works!!!!";

xlWorkBook.SaveAs(name, 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);
}

private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception occurred while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}[/code]

<span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small
<br/>


<span style="font-family:Consolas; font-size:x-small
<span style="font-family:Consolas; font-size:x-small



View the full article
 
Back
Top