這篇文章主要介紹了ASP.NET中 Execl導出的六種方法實例,有需要的朋友可以參考一下
代碼如下: /// <summary> /// 導出Excel /// </summary> /// <param name="page"></param> /// <param name="dt"></param> //方法一: public void ImportExcel(Page page, DataTable dt) { try { string filename = Guid.NewGuid().ToString() + ".xls"; string webFilePath = page.Server.MapPath("/" + filename); CreateExcelFile(webFilePath, dt); using (FileStream fs = new FileStream(webFilePath, FileMode.OpenOrCreate)) { //讓用戶輸入下載的本地地址 page.Response.Clear(); page.Response.Buffer = true; page.Response.Charset = "GB2312"; //page.Response.AppendHeader("Content-Disposition", "attachment;filename=MonitorResult.xls"); page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename); page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); page.Response.ContentType = "application/ms-excel"; // 讀取excel數據到內存 byte[] buffer = new byte[fs.Length - 1]; fs.Read(buffer, 0, (int)fs.Length - 1); // 寫到aspx頁面 page.Response.BinaryWrite(buffer); page.Response.Flush(); //this.ApplicationInstance.CompleteRequest(); //停止頁的執行 fs.Close(); fs.Dispose(); //刪除臨時文件 File.Delete(webFilePath); } } catch (Exception ex) { throw ex; } } 方法二: 代碼如下: public void ImportExcel(Page page, DataSet ds) { try { string filename = Guid.NewGuid().ToString() + ".xls"; string webFilePath = page.Server.MapPath("/" + filename); CreateExcelFile(webFilePath, ds); using (FileStream fs = new FileStream(webFilePath, FileMode.OpenOrCreate)) { //讓用戶輸入下載的本地地址 page.Response.Clear(); page.Response.Buffer = true; page.Response.Charset = "GB2312"; //page.Response.AppendHeader("Content-Disposition", "attachment;filename=MonitorResult.xls"); page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename); page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); page.Response.ContentType = "application/ms-excel"; // 讀取excel數據到內存 byte[] buffer = new byte[fs.Length - 1]; fs.Read(buffer, 0, (int)fs.Length - 1); // 寫到aspx頁面 page.Response.BinaryWrite(buffer); page.Response.Flush(); //this.ApplicationInstance.CompleteRequest(); //停止頁的執行 fs.Close(); fs.Dispose(); //刪除臨時文件 File.Delete(webFilePath); } } catch (Exception ex) { throw ex; } } 方法三: 代碼如下: public void ImportExcel(Page page, DataTable dt1, DataTable dt2, string conditions) { try { string filename = Guid.NewGuid().ToString() + ".xls"; string webFilePath = page.Ser