ASP tutorial. NET C # generating Excel file methods
HANDLER.ASHX: Generating dynamic Excel Files
public class Handler:ihttphandler {
public void ProcessRequest (HttpContext context) {
Context. Response.ContentType = "Application/octet-stream";
string filename = Httputility.urlencode ("dynamically generated. xls");
Context. Response.AddHeader ("Content-disposition", String. Format ("attachment:filename={0}", filename));
Who can help me explain the above bold code, features I know, but need a little more explanation, first thank you ha
}
public bool IsReusable {
get {
return false;
}
}
}
Finally, you chose to use Office Excel Automation services to build Excel files by using the COM objects that Excel provides.
The specific code is as follows:
public static void Createexcel ()
{
for (int i = 0; i<1 i++)
{
String stafile = "D:testx";
System.Reflection.Missing miss = System.Reflection.Missing.Value;
Excel.applicationclass m_objexcel = new Excel.applicationclass ();
M_objexcel.visible = false;
Excel.Workbooks m_objbooks = (excel.workbooks) m_objexcel.workbooks;
Excel.Workbook m_objbook = (Excel.Workbook) (M_objbooks.add (Miss));
Excel.Worksheet m_objsheet = (excel.worksheet) m_objbook.activesheet;
Writing data to an Excel file
Excel.Range er = m_objsheet.get_range ((object) "A1", System.Reflection.Missing.Value);
Er. Value2 = "DFADFA";
m_objBook.SaveAs (stafile+i.tostring () + ". xls", Miss, Miss, Miss, Miss,miss, Excel.XlSaveAsAccessMode.xlNoChange, Miss , Miss,miss, Miss, Miss);
M_objbook.close (false, Miss, Miss);
M_objbooks.close ();
M_objexcel.quit ();
System.Runtime.InteropServices.Marshal.ReleaseComObject (ER);
System.Runtime.InteropServices.Marshal.ReleaseComObject (M_objsheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (M_objbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject (m_objbooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject (M_objexcel);
Gc. Collect ();
}
}
A similar approach has been seen on the web, but they all have a problem that cannot be released after using Excel, and after research I have found that when using COM objects, you must release every instance object that you set up, which is the red part of the code.