using XL = Microsoft.Office.Interop.Excel;
void CreateExcel()
{
string filename = @"C:\ExcelThroughCSharp.xls";
// create an instance of EXCEL application
XL.Application app = new XL.Application();
app.Visible = true;
app.DisplayAlerts = true;
// add workbook
XL.Workbook wb = app.Workbooks.Add(XL.XlWBATemplate.xlWBATWorksheet);
// the wb workbook already has 1 worksheet
// add second worksheet after the first one
wb.Worksheets.Add(Type.Missing, wb.Worksheets[wb.Worksheets.Count], Type.Missing, Type.Missing);
// add second worksheet after the second one
wb.Worksheets.Add(Type.Missing, wb.Worksheets[wb.Worksheets.Count], Type.Missing, Type.Missing);
// get the second worksheet
XL.Worksheet sheet = (XL.Worksheet)wb.Worksheets[2];
// write some value
sheet.Cells[2, 2] = "test value from c# code";
// change worksheet's name
sheet.Name = "modified sheet";
// close and save the workbook
wb.Close(true, filename, null);
// release the worksheet resources
if (sheet != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);sheet = null;
}
// release the workbook resources
if (wb != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);wb = null;
}
// release the excel instance resources
if (app != null)
{
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
}
// Clean up memory so Excel can shut down.
GC.Collect(); GC.WaitForPendingFinalizers();
// The GC needs to be called twice in order to get the
// Finalizers called - the first time in, it simply makes
// a list of what is to be finalized, the second time in,
// it actually the finalizing. Only then will the
// object do its automatic ReleaseComObject.
GC.Collect();GC.WaitForPendingFinalizers();
}
CREDITS: http://bytes.com/forum/thread475347.html