後臺列表導出Excel
阿新 • • 發佈:2018-07-31
控制 url indexof get star asc catch pub text
小白做的導出功能
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; } }
後臺列表導出Excel