时间:2021-07-01 10:21:17 帮助过:29人阅读
后台代码
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using NPOI; using NPOI.SS.UserModel; using System.IO; public partial class 导出到Excel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { DataTable dt =//利用你的orm框架得到数据源DataTable if (dt.Rows.Count > 0) { //创建工作簿 NPOI.SS.UserModel.IWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); //创建表 ISheet sheet = workbook.CreateSheet("vinkong");//表名 IRow row0 = sheet.CreateRow(0); row0.CreateCell(0).SetCellValue("id信息"); row0.CreateCell(1).SetCellValue("名称信息"); row0.CreateCell(2).SetCellValue("备注信息"); for (int r = 0; r < dt.Rows.Count; r++) { //创建行接受DataTable的行数据 IRow row = sheet.CreateRow(r + 1); row.CreateCell(0).SetCellValue(dt.Rows[r]["ID"].ToString()); row.CreateCell(1).SetCellValue(dt.Rows[r]["Code"].ToString()); row.CreateCell(2).SetCellValue(dt.Rows[r]["Name"].ToString()); } string filePath = Server.MapPath(@"./Files/vinkong" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");//存到项目Files文件夹下 //写文件 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); //下载 FileInfo fileInfo = new FileInfo(filePath); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName); Response.Flush(); //删除文件 System.IO.File.Delete(filePath); Response.End(); } else { Response.Write("<script>alert(‘导出失败!‘)</script>"); } } }
WEB版利用NPOI导出数据库数据为Excel文件
标签:data 导出数据 linq eric add oct model str get