利用 NUget包 EPPlus 实现数据导出到Excel(适用于DTcms)
首先安装EPPlus 包
Install-Package EPPlus
然后在需要导出的页面引用以下命名空间
using OfficeOpenXml; using OfficeOpenXml.Drawing; using OfficeOpenXml.Drawing.Chart; using OfficeOpenXml.Style; using System.IO;
以下为本人项目中用到的导出数据处理部分,仅供参考:
var path = HttpContext.Current.Server.MapPath("");//获取文件的路径信息 using(var fileStream = new FileStream(path +"../../../File/myexcel.xls",FileMode.Create)){ BLL.article_comment bll = new BLL.article_comment(); DataTable list = bll.GetList_out("channel_id=" + this.channel_id, "add_time desc").Tables[0];//获取需要导出的数据 var pack = new ExcelPackage(); var ws = pack.Workbook.Worksheets.Add("客户留言导出数据表");//新建表格 var col = 1; var row = 1; ws.Cells[1, 1].Value = "用户名"; ws.Cells[1, 2].Value = "省份"; ws.Cells[1, 3].Value = "是否开店"; ws.Cells[1, 4].Value = "电话"; ws.Cells[1, 5].Value = "申请时间";//表格头部 row++; //循环写入数据到表格 foreach (var coachBatchPayoutExcelModel in list.AsEnumerable()) { var s = 2; for (var i = 1; i < 6; i++) { var colName = ws.Cells[1, i].Value.ToString(); ws.Cells[row, i].Value = coachBatchPayoutExcelModel.ItemArray[s] == null ? "" : coachBatchPayoutExcelModel.ItemArray[s].ToString(); s++; } row++; } var byarrary = pack.GetAsByteArray(); fileStream.Write(byarrary, 0, byarrary.Length); fileStream.Flush(); };
//以下为输出文件的代码 FileInfo file = new FileInfo(path + "../../../File/myexcel.xls");//路径 Context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码 Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("myexcel.xls")); //解决中文文件名乱码 Context.Response.AddHeader("Content-length", file.Length.ToString()); Context.Response.ContentType = "application/vnd.ms-excel";//MIME类型 Context.Response.WriteFile(file.FullName); Context.Response.End();