1.安装nuget包
2.封装方法
public byte[] ExportToByteArray(IEnumerable<string> headerText, IEnumerable<string[]> dataList, string extraMessage = null) { IWorkbook workbook = Write(headerText, dataList, extraMessage); var memoryStream = new MemoryStream(); workbook.Write(memoryStream); return memoryStream.ToArray(); } private static IWorkbook Write(IEnumerable<string> headerText, IEnumerable<string[]> dataList, string extraMessage = null) { IWorkbook wb = new XSSFWorkbook(); ISheet sheet = wb.CreateSheet("Sheet1"); var rowIndex = 0; if (!string.IsNullOrEmpty(extraMessage)) { SetExcelRowForExtraMessage(sheet, extraMessage); rowIndex += 1; } SetExcelHeaderRow(sheet, rowIndex, headerText.ToList()); rowIndex += 1; if (!dataList.Any()) { return wb; } for (var i = 0; i < dataList.Count(); i++) { SetExcelBodyRow(sheet, rowIndex + i, dataList.ElementAt(i)); } //优化表格的列宽 int maxColumnIndex = dataList.Max(row => row.Count()); for (var i = 0; i < maxColumnIndex; i++) { sheet.AutoSizeColumn(i); } return wb; }
3.Controller调用方法
/// <summary> /// 基金净值下载 /// </summary> [HttpGet] public HttpResponseMessage DownloadExecl() { try { //获取数据 var productList = _productService.GetProductList(); var exportData = ProductList.Select(t => new { t.Date, t.Name }).ToList(); //下载文件 var fileName = $"{DateTime.Today:yyyyMMdd}.xlsx"; var bytes = _exportor.ExportToByteArray(HeaderText, exportData, ""); var response = GetFileResponse(fileName, bytes); return response; } catch (Exception) { return new HttpResponseMessage(System.Net.HttpStatusCode.NoContent); } } private HttpResponseMessage GetFileResponse(string fileName, byte[] bytes) { HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK); var mime = System.Web.MimeMapping.GetMimeMapping(fileName); var stream = new MemoryStream(bytes); response.Content = new StreamContent(stream); response.Content = new StreamContent(stream); bool isFirefox = Request.Headers.UserAgent.ToString() .IndexOf("Firefox", StringComparison.CurrentCultureIgnoreCase) > -1; response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mime); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = isFirefox ? fileName : HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) }; response.Content.Headers.ContentLength = stream.Length; return response; } /// <summary> /// Excel列头 /// </summary> private static readonly string[] HeaderText = { "时间", "名称" };
ASP.NET MVC
ACTION
/// <summary> /// Action /// </summary> public FileResult ExportExcel(string name) { var results = new List<Student> { new Student {Name = "james",Address = "Los Angeles"}, new Student {Name = "londo",Address = "Cleveland"} }; var dt = new DataTable(); dt.Columns.Add("姓名"); dt.Columns.Add("地址"); foreach (var item in results) { DataRow dr = dt.NewRow(); dr["姓名"] = item.Name; dr["地址"] = item.Address; dt.Rows.Add(dr); } var stream = ExcelUtil.TableToExcel(dt); return File(stream, "application/x-xls", "学生信息.xls"); }
common
using System.Data; using System.IO; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; namespace Common { /// <summary> /// Excel 数据导出、导入 /// </summary> public static class ExcelUtil { /// <summary> /// Datable导出成Excel /// </summary> /// <param name="dt"></param> /// <param name="file">导出路径(包括文件名与扩展名)</param> public static byte[] TableToExcel(DataTable dt) { IWorkbook workbook; workbook = new HSSFWorkbook(); //if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { ; } else { workbook = null; } //if (workbook == null) { return null; } ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName); //表头 IRow row = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = row.CreateCell(i); cell.SetCellValue(dt.Columns[i].ColumnName); } //数据 for (int i = 0; i < dt.Rows.Count; i++) { IRow row1 = sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ICell cell = row1.CreateCell(j); cell.SetCellValue(dt.Rows[i][j].ToString()); } } //转为字节数组 MemoryStream stream = new MemoryStream(); workbook.Write(stream); var buf = stream.ToArray(); return buf; } } }
前端调用:
无参
// 导出 $(".export_btn").click(function () { window.open("/controller/action"); })
有参:
$('#export_btn').click(function () { var url ="/controller/action"; url += "?a=" + $('#a').val(); url += "&b=" + $('#b').val(); window.open(url); });
导入
/// <summary> /// 导入 /// </summary> public JsonResult ImportPdm(HttpPostedFileBase file) { var fileName = file?.FileName; var msg = string.IsNullOrWhiteSpace(fileName) ? "上传文件为空" : $"{fileName} 上传成功"; List<Pdm> data = ReadFromExcel(file, GetPdm); return Json(new { Msg = msg }); } private List<Pdm> ReadFromExcel(HttpPostedFileBase httpPostedFileBase, Func<IRow, int, Pdm> convertToPdm) { var list = new List<Pdm>(); IWorkbook wk = null; string extension = System.IO.Path.GetExtension(httpPostedFileBase.FileName)?.ToLower(); if (extension != null && extension.Equals(".xls")) { wk = new HSSFWorkbook(httpPostedFileBase.InputStream); } else { wk = new XSSFWorkbook(httpPostedFileBase.InputStream); } ISheet sheet = wk.GetSheetAt(0); // 第0个sheet int offset = 1; for (int i = offset; i <= sheet.LastRowNum; i++) { var model = convertToPdm(sheet.GetRow(i), i + 1); if (model == null) break; list.Add(model); } return list; } private Pdm GetPdm(IRow row, int index) { var model = new Pdm(); SetCellType(row, CellType.String); model.TechnologyName = row.GetCell(0).StringCellValue.Trim(); model.Number = row.GetCell(1).StringCellValue.Trim(); model.Workshop = row.GetCell(2).StringCellValue.Trim(); return model; } private void SetCellType(IRow row, CellType type) { row.GetCell(0).SetCellType(type); row.GetCell(1).SetCellType(type); row.GetCell(2).SetCellType(type); }