How does Asp.net call Excel?
1. Reference Microsoft. Office. Interop. Excel. dll, automatically packaged as Interop. Microsoft. Office. Interop. Excel. dll
2. Code:
/// <Summary>
/// Generate an excel report
/// </Summary>
Private void CreateExcelReport ()
{
String xlTemplateFullPath = Server. MapPath ("~ /Function/Business/ExcelTemplate/OTOCFPY.xls ");
String xlSavePath = Server. MapPath ("~ /Function/Business/ExcelReport ");
_ Application xlApp = null;
_ Workbook xlWorkbook = null;
_ Worksheet xlWorksheet = null;
System. Reflection. Missing oMissing = System. Reflection. Missing. Value;
Try
{
XlApp = new ApplicationClass ();
XlWorkbook = xlApp. Workbooks. Open (xlTemplateFullPath,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing,
OMissing );
XlWorksheet = (Worksheet) xlWorkbook. Worksheets [1];
XlSavePath = Path. Combine (xlSavePath, DateTime. Now. Ticks. ToString ());
// Write excel Data
WriteData (xlWorksheet );
XlWorkbook. SaveAs (xlSavePath, oMissing,
OMissing, Microsoft. Office. Interop. Excel. XlSaveAsAccessMode. xlShared, oMissing,
OMissing, oMissing );
XlApp. Visible = true;
XlApp. Quit ();
// Send an excel file to the client
Response. Clear ();
Response. Buffer = true;
Response. ContentType = "application/ms-excel ";
Response. AppendHeader ("Content-Disposition", "attachment?filename=todaydownlist.xls ");
System. IO. FileInfo fileInfo = new FileInfo (xlSavePath + ". xls ");
Response. AddHeader ("Content-Length", fileInfo. Length. ToString ());
Response. WriteFile (fileInfo. FullName );
Response. End ();
}
Catch (Exception ex)
{
Response. Write (ex. Message );
}
Finally
{
System. Runtime. InteropServices. Marshal. ReleaseComObject (xlApp );
XlApp = null;
GC. Collect ();
}
}
Notes
Excel used upBe sure to release excel later