public class NpoiMemoryStream : MemoryStream { public NpoiMemoryStream() { AllowClose = true; } public bool AllowClose { get; set; } public override void Close() { if (AllowClose) base.Close(); } }
public ActionResult Export() { int orderId = base.Id; Orders order = OrdersModel.GetInstance.GetById(orderId); var workbook = new XSSFWorkbook(Server.MapPath("~/Template/order.xlsx")); var sheet = workbook.GetSheetAt(0); IRow row = sheet.CreateRow(4); row.CreateCell(0).SetCellValue("货号"); row.CreateCell(1).SetCellValue("品名"); row.CreateCell(2).SetCellValue("颜色"); string fname = string.Format("{0}.xlsx", order.OrderNo); //导出Excel文件的方法 var ms = new NpoiMemoryStream(); ms.AllowClose = false; workbook.Write(ms); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); ms.AllowClose = true; return File(ms, "application/vnd.ms-excel", fname); }