First , Add Reference " Microsoft Excel 10.0 Object Library"
private void CreateExcelWorkbook(DataTable dt)
{
string strCurrentDir = Server.MapPath(".") + "\\";
//RemoveFiles(strCurrentDir); // utility method to clean up old files
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
GC.Collect();// clean up any other excel guys hangin' around...
oXL = new Excel.Application();
oXL.Visible = false;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
// Create Header and sheet...
//for (int j = 0; j < myReader.FieldCount; j++)
//{
// oSheet.Cells[1, j + 1] = myReader.GetName(j).ToString();
//}
// build the sheet contents
for(int i=0;i<dt.Rows.Count;i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
oSheet.Cells[i+1, k+1] = dt.Rows[i][k].ToString();
}
}// end while
oSheet.Name = "my";
//Format A1:Z1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "Z1").Font.Bold = true;
oSheet.get_Range("A1", "Z1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
//AutoFit columns A:Z.
oRng = oSheet.get_Range("A1", "Z1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
string strFile = "report" + System.DateTime.Now.Ticks.ToString() + ".xls";
oWB.SaveAs(strCurrentDir + strFile, Excel.XlFileFormat.xlWorkbookNormal,
null, null, false, false, Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);
// Need all following code to clean up and extingush all references!!!
oWB.Close(null, null, null);
oXL.Workbooks.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);
oSheet = null;
oWB = null;
oXL = null;
GC.Collect(); // force final cleanup!
//string strMachineName = Request.ServerVariables["SERVER_NAME"];
//errLabel.Text = "<A href=http://" + strMachineName + "/ExcelGen/" + strFile + ">Download Report</a>";
Response.Write("success!");
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
Response.Write(errorMessage);
}
}