文章目錄
- 1、helper
- 2、control
- 3、前端 axios
記錄webapi excel 導出File示例
.NET8.0 NPOI2.73
1、helper
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IO;
/// <summary>
/// 導出EXCEL
/// </summary>
public class ExcelHelper
{/// <summary>/// 導出EXCEL/// </summary>public static MemoryStream Export(DataTable dataTable){IWorkbook workbook = new XSSFWorkbook();ISheet sheet = workbook.CreateSheet("Sheet1");// 創建表頭IRow headerRow = sheet.CreateRow(0);foreach (DataColumn column in dataTable.Columns){ICell cell = headerRow.CreateCell(column.Ordinal);cell.SetCellValue(column.ColumnName);}// 填充數據行int rowIndex = 1;foreach (DataRow row in dataTable.Rows){IRow dataRow = sheet.CreateRow(rowIndex++);foreach (DataColumn column in dataTable.Columns){ICell cell = dataRow.CreateCell(column.Ordinal);cell.SetCellValue(row[column].ToString());}}// 將工作簿寫入內存流MemoryStream stream = new MemoryStream();workbook.Write(stream);return stream;}
}
2、control
[Route("api/[controller]/[action]")][ApiController]public class UserController : ControllerBase{/// <summary>///導出/// </summary>[HttpGet("export")]public async Task<IActionResult> ExportExcel(){DataTable dt = await _Users.GetAll();var stream = ExcelHelper.Export(dt);string name = DateTime.Now.ToString("yyyyMMddHHmmss");return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", name+".xlsx");}}
3、前端 axios
//-按鈕<Button type="success" @click="ExlAction">導出</Button>
//-接口
export const ExportApi = () => {return request.get({ url: '/User/ExportExcel/export', responseType: 'blob' })
}
//-調用
const ExlAction = async () => {const res = await ExportApi() //導出數據if (res) {const contentDisposition = res.headers['content-disposition']let filename = 'exported-file.xlsx'if (contentDisposition) {const matches = /filename="?([^;]+)"?/.exec(contentDisposition)if (matches && matches[1]) {filename = matches[1]}}const url = window.URL.createObjectURL(new Blob([res.data]))const link = document.createElement('a')link.href = urllink.setAttribute('download', filename)document.body.appendChild(link)link.click()link.remove()}
}