public ActionResult ExportToExcel() { var package = new ExcelPackage();//是一个epplus中的类 var worksheet = package.Workbook.Worksheets.Add("Sheet1");//Workbook 是 Excel 工作簿,Worksheets 是工作簿中的工作表集合 // 添加表头 cell代表表格或单元格 worksheet.Cells[1, 1].Value = "姓名"; worksheet.Cells[1, 2].Value = "年龄"; worksheet.Cells[1, 3].Value = "性别"; // 添加数据 worksheet.Cells[2, 1].Value = "张三"; worksheet.Cells[2, 2].Value = 20; worksheet.Cells[2, 3].Value = "男"; worksheet.Cells[3, 1].Value = "李四"; worksheet.Cells[3, 2].Value = 25; worksheet.Cells[3, 3].Value = "女"; // 自适应列宽 worksheet.Cells.AutoFitColumns(); // 导出 Excel 文件 var fileStream = new MemoryStream(package.GetAsByteArray()); var fileName = "export.xlsx"; var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; return View(new FileViewModel { FileStream = fileStream, ContentType = contentType, FileName = fileName }); }@model该怎么写
时间: 2023-05-17 09:03:08 浏览: 142
您可以这样写:
public class FileViewModel
{
public MemoryStream FileStream { get; set; }
public string ContentType { get; set; }
public string FileName { get; set; }
}
public ActionResult ExportToExcel()
{
var package = new ExcelPackage();
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells[1, 1].Value = "姓名";
worksheet.Cells[1, 2].Value = "年龄";
worksheet.Cells[1, 3].Value = "性别";
worksheet.Cells[2, 1].Value = "张三";
worksheet.Cells[2, 2].Value = 20;
worksheet.Cells[2, 3].Value = "男";
worksheet.Cells[3, 1].Value = "李四";
worksheet.Cells[3, 2].Value = 25;
worksheet.Cells[3, 3].Value = "女";
worksheet.Cells.AutoFitColumns();
var fileStream = new MemoryStream(package.GetAsByteArray());
var fileName = "export.xlsx";
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return View(new FileViewModel { FileStream = fileStream, ContentType = contentType, FileName = fileName });
}
阅读全文