这篇文章主要介绍了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