/// <summary> /// 导出Excel(使用模板) /// </summary> /// <returns></returns> [HttpGet] public IActionResult ExportExcelByTemplate() { try { IWorkbook wb = null; var template = Directory.GetCurrentDirectory() + @"\wwwroot\Template\template.xlsx"; // 按模板内容创建 IWorkbook using(FileStream fs = new FileStream(template, FileMode.OpenOrCreate)) { wb = new XSSFWorkbook(fs); } var list = db.Stu.Where(s => s.IsOk).ToList(); ISheet sheet = wb.GetSheetAt(0); int i = 1; IRow row = null; foreach (var item in list) { row = sheet.CreateRow(i); row.CreateCell(0).SetCellValue(item.StuName); row.CreateCell(1).SetCellValue(item.Sex == 0 ? "男" : "女"); row.CreateCell(2).SetCellValue(double.Parse(item.Phone)); row.CreateCell(3).SetCellValue(item.CId); // 日期格式的导出 ICell cell = row.CreateCell(4); ICellStyle style = wb.CreateCellStyle(); IDataFormat format = wb.CreateDataFormat(); style.DataFormat = format.GetFormat("yyyy-MM-dd"); cell.CellStyle = style; cell.SetCellValue(DateTime.Parse(item.InDate.ToString("yyyy-MM-dd"))); row.CreateCell(5).SetCellValue((double)item.JF); row.CreateCell(6).SetCellValue(item.Pic); row.CreateCell(7).SetCellValue(item.State); i++; } byte[] buffer = null; using (MemoryStream ms = new MemoryStream()) { wb.Write(ms); buffer = ms.ToArray(); } // .xlsx文件对应的Mime信息 var mime = new FileExtensionContentTypeProvider().Mappings[".xlsx"]; return File(buffer, mime, "学生信息.xlsx"); } catch (Exception) { throw; } }标签:wb,C#,Excel,item,CreateCell,new,SetCellValue,模板,row From: https://www.cnblogs.com/lixia0604/p/18089544