1.下载破解版Aspose.Cells ,正版 需要授权需要收费,使用的话会有水印。 Aspose.Cells相比NPOI 多了模版语法功能,还是很实用的。对于复杂表格来说。
2.在webapi 项目中新建文件夹 复制 Aspose.Cells .dll ,并添加引用。
/// <summary> /// 返回Excel文件流 /// </summary> /// <param name="model">数据</param> /// <param name="templateFileName">模板文件,要全路径</param> /// <param name="sheetName">工作簿名称</param> /// <param name="outDesigner">工作簿名称</param> /// <returns></returns> public static byte[] OutDataTableToStream(DataTable dt, string templateFileName) { dt.TableName = "dt"; string fileName = Path.GetFileName(templateFileName); Workbook wb = new Workbook(templateFileName); WorkbookDesigner designer = new WorkbookDesigner(wb); designer.SetDataSource(dt); designer.Process(); return designer.Workbook.SaveToStream().ToArray(); }
传入一个datatble ,并输出 byte[]
/// <summary> /// 导出dt /// </summary> /// <param name="dt"></param> /// <returns></returns> public HttpResponseMessage ExportDtCsv(DataTable dt, string fileTemplateName) { HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Forbidden); string templateFileName = HttpContext.Current.Server.MapPath("~/bin/template/" + fileTemplateName); byte[] bytes = Util.OutDataTableToStream(dt, templateFileName); string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new ByteArrayContent(bytes); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = fileName; return result; }
输出 HttpResponseMessage 前端调用即可。
模版语法
&= 是可以循环的,&=$ 是直接绑定变量的,不用循环的
前端直接调用
uploadFile (url, param) { let paramStr = Http.spliceParam(param); let curUrl = Http.baseUrl() + url + paramStr; window.open(curUrl); }
就能下载了