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对象的时候一定要把每一个建立的实例对象都释放掉,也就是代码中红色的部分。