小白做的导出功能
js部分:
function btn_export() { dialogConfirm("注:您确定要导出报表吗?", function (r) { if (r) { Loading(true, "正在导出..."); window.setTimeout(function () { $.ajax({ url: "", type: "post", data: { start_date:$("#start_date").val(), end_date:$("#end_date").val() }, dataType: "json", success: function (result) { if (result.code != 200) { dialogMsg(result.msg, 0); Loading(false); return; } Loading(false); dialogMsg(result.msg, 1); window.location = result.path; } }); }, 1000); } }); }
控制器部分:
public ActionResult ExportExcel(string start_date,string end_date) { string path = ""; string result= excelexport.ExcelExport(start_date, end_date,ref path); object obj = new { code = 200, path = path, msg = "导出成功" }; if (result!= "") { obj = new { code = 400, msg = result, }; } return Json(obj, JsonRequestBehavior.AllowGet); }
BLL部分: 引入using System.IO和using NPOI.XSSF.UserModel,在解决方案下添加一个空文件夹derivation 和一个带有标题栏的excel文件的stencil文件夹,excel文件里的标题要跟代码循环部分数据对齐
public string ExcelExport(string start_date, string end_date,ref string path) { var bus = new { all = true, start_date, end_date }; var res = dbFactory.GetData(0, out dynamic out_dynamic, bus); if (res != "") return "无数据"; try { string templetFileName = HttpContext.Current.Server.MapPath("~\\stencil\\数据报表.xlsx"); string name = DateTime.Now.ToString("yyyy-MM-dd") + "数据报表.xlsx"; path = "/derivation/" + name; string reportFileName = HttpContext.Current.Server.MapPath("~\\derivation\\" + name); FileStream file = new FileStream(templetFileName, FileMode.Open, FileAccess.Read); XSSFWorkbook hssfworkbook = new XSSFWorkbook(file); var sheet = hssfworkbook.GetSheet("Sheet1"); var list = out_dynamic.list; int index = 0; foreach (var item in list) { index = list.IndexOf(item) + 1; sheet.CreateRow(index).CreateCell(0); var row = sheet.GetRow(index); row.GetCell(0).SetCellValue(item.id.ToString()); row.CreateCell(2); row.GetCell(2).SetCellValue(item.name.ToString()); row.CreateCell(3); row.GetCell(3).SetCellValue(item.value.ToString()); row.CreateCell(4); row.GetCell(4).SetCellValue(item.price.ToString()); row.CreateCell(5); row.GetCell(5).SetCellValue(item.start_addr_name.ToString()); row.CreateCell(6); row.GetCell(6).SetCellValue(item.end_addr_name.ToString()); row.CreateCell(8); row.GetCell(8).SetCellValue(item.create_date.ToString()); } index++; sheet.CreateRow(index).CreateCell(0); sheet.GetRow(index).GetCell(0).SetCellValue("总计:" + list.Count + "条"); using (FileStream filess = File.OpenWrite(reportFileName)) { hssfworkbook.Write(filess); } file.Close(); return ""; } catch (Exception ex) { return ex.Message; } }
原文地址:https://www.cnblogs.com/lemonmoney/p/9394063.html
时间: 2024-10-09 17:36:08