.Net Core WebApi+Vue实现文件下载
WebApi 控制器代码实例
using OfficeOpenXml;引用的程序集
[HttpPost]
public async Task<IActionResult> AcceptanceExportDate(AcceptanceEntryRequest input)
{
List<AcceptanceEntryResponse> exports = await _acceptanceEntryBusiness.AcceptanceExport(input);//获取到你所要下载数据,我这里调用查询接口
using var package = new ExcelPackage();
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("信息表");
List<string> titles = new List<string>
{
"客户公司",
"销售公司",
};//标题
for (int i = 0; i < titles.Count; i++)
{
worksheet.Cells[1, i + 1].Value = titles[i];
}
int row = 2, col = 0;
//内容
for (int i = 0; i < exports.Count; i++)
{
var Accptance = exports[i];
col = titles.IndexOf("客户公司") + 1; SetValue(worksheet, row, col, row, col, Accptance.CompanyName);
col = titles.IndexOf("销售公司") + 1; SetValue(worksheet, row, col, row, col, Accptance.SaleCompanyName);
row++;
}
var excelData = package.GetAsByteArray();
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var fileName = "信息表.xlsx";
return File(excelData, contentType, fileName);
}
public void SetValue(ExcelWorksheet worksheet, int row, int col, int endRow, int endCol, string text)
{
var range = worksheet.Cells[row, col, endRow, endCol];
range.Merge = true;
range.Value = text;
}
Vue代码实例
this.queryParam是你的查询条件
<a-button type="primary" @click="AcceptanceExport">导出</a-button>
AcceptanceExport () {
this.loading = true
this.$http
.post('/EShop/AcceptanceEntry/AcceptanceExportDate', this.queryParam, { responseType: 'blob' })
.then((resJson) => {
this.loading = false
const blob = new Blob([resJson])
const fileName = '信息表.xls'
if ('download' in document.createElement('a')) {
// 非IE下载
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
elink.setAttribute('download', '信息表.xlsx')
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName)
}
})
}