asp教程.net c#產生excel檔案方法
Handler.ashx:產生動態Excel檔案
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/octet-stream";
string filename = HttpUtility.UrlEncode("動態產生.xls");
context.Response.AddHeader("Content-disposition",string.Format("attachment:filename={0}",filename));
//誰能幫我解釋一下上面加粗的這句代碼,功能我知道,但需要詳細一點的解釋,先謝謝哈
}
public bool IsReusable {
get {
return false;
}
}
}
最後選擇了使用OFFICE 的Excel 自動化服務來產生Excel檔案的辦法,也就是使用Excel提供的Com對象。
具體的代碼如下:
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;
//向Excel檔案中寫入資料
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();
}
}
在網上也看到過類似的辦法,但是他們都存在著一個使用完Excel後無法釋放的問題;在我經過研究後發現在使用Com對象的時候一定要把每一個建立的執行個體對象都釋放掉,也就是代碼中紅色的部分。