要导出这样一个Excel表格:
1.后端API下载安装包:
EPPlus
2.后端代码
点击查看代码
/// <summary>
/// 接口
/// </summary>
/// <returns>结果</returns>
[HttpGet]
public IActionResult ExportTab()
{
var list = _db.ExcelTab.ToList();
var ms=new MemoryStream();
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package =new ExcelPackage() )
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Workbook.Properties.SetCustomPropertyValue("Lauguage", "zh-CN");
worksheet.Cells["A1"].Value = "表单名称";
worksheet.Cells["B1"].Value = "表单类型";
worksheet.Cells["C1"].Value = "参数1";
worksheet.Cells["D1"].Value = "参数2";
worksheet.Cells["E1"].Value = "参数3";
for(int i = 0; i < list.Count; i++)
{
worksheet.Cells["A"+(i+2)].Value = list[i].Name;
worksheet.Cells["B"+(i+2)].Value = list[i].Type;
worksheet.Cells["C"+(i+2)].Value = list[i].ParamOne;
worksheet.Cells["D"+(i+2)].Value = list[i].ParamTwo;
worksheet.Cells["E"+(i+2)].Value = list[i].ParamThree;
}
package.SaveAs(ms);
}
ms.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = "用户填表表单.xlsx"
};
}
点击查看代码
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
3.前端代码
只需在前端加入一个按钮,并加上一个单击事件,在单击事件里写上一句代码:
点击查看代码
location.href = "http://localhost:17801/api/Tab/ExportTab";