Vue+axios+WebApi+NPOI導(dǎo)出Excel文件實(shí)例方法
一、前言
項(xiàng)目中前端采用的Element UI 框架, 遠(yuǎn)程數(shù)據(jù)請(qǐng)求,使用的是axios,后端接口框架采用的asp.net webapi,數(shù)據(jù)導(dǎo)出成Excel采用NPOI組件。其業(yè)務(wù)場景,主要是列表頁(如會(huì)員信息,訂單信息等)表格數(shù)據(jù)導(dǎo)出,如表格數(shù)據(jù)進(jìn)行了條件篩選,則需要將條件傳至后端api,篩選數(shù)據(jù)后,導(dǎo)出成Excel。
思考過前端導(dǎo)出的3種方案:
1.使用location.href 打開接口地址.缺點(diǎn): 不能傳token至后端api, 無法保證接口的安全性校驗(yàn),并且接口只能是get方式請(qǐng)求.
2.采用axios請(qǐng)求接口,先在篩選后的數(shù)據(jù)服務(wù)端生成文件并保存,然后返回遠(yuǎn)程文件地址,再采用 location.href打開文件地址進(jìn)行下載. 缺點(diǎn): 實(shí)現(xiàn)復(fù)雜,并且每次導(dǎo)出會(huì)在服務(wù)端生成文件,但是又沒有合適的時(shí)機(jī)再次觸發(fā)刪除文件,會(huì)在服務(wù)端形成垃圾數(shù)據(jù)。優(yōu)點(diǎn):每次導(dǎo)出都可以有記錄。
3. 采用axios請(qǐng)求接口,服務(wù)端api返回文件流,前端接收到文件流后,采用blob對(duì)象存儲(chǔ),并創(chuàng)建成url, 使用a標(biāo)簽下載. 優(yōu)點(diǎn):前端可傳token參數(shù)校驗(yàn)接口安全性,并支持get或post兩種方式。
因其應(yīng)用場景是導(dǎo)出Excel文件之前,必須篩選數(shù)據(jù),并需要對(duì)接口安全進(jìn)行校驗(yàn),所以第3種方案為最佳選擇。在百度之后,發(fā)現(xiàn)目前使用最多的也是第3種方案。
二、Vue + axios 前端處理
1.axios 需在response攔截器里進(jìn)行相應(yīng)的處理(這里不再介紹axios的使用, 關(guān)于axios的用法,具體請(qǐng)查看Axios中文說明 ,我們在項(xiàng)目中對(duì)axios進(jìn)行了統(tǒng)一的攔截定義). 需特別注意: response.headers['content-disposition'],默認(rèn)是獲取不到的,需要對(duì)服務(wù)端webapi進(jìn)行配置,請(qǐng)查看第三點(diǎn)中webapi CORS配置
// respone攔截器
service.interceptors.response.use(
response => {
// blob類型為文件下載對(duì)象,不論是什么請(qǐng)求方式,直接返回文件流數(shù)據(jù)
if (response.config.responseType === 'blob') {
const fileName = decodeURI(
response.headers['content-disposition'].split('filename=')[1]
)
// 返回文件流內(nèi)容,以及獲取文件名, response.headers['content-disposition']的獲取, 默認(rèn)是獲取不到的,需要對(duì)服務(wù)端webapi進(jìn)行配置
return Promise.resolve({ data: response.data, fileName: fileName })
}
// 依據(jù)后端邏輯實(shí)際情況,需要彈窗展示友好錯(cuò)誤
},
error => {
let resp = error.response
if (resp.data) {
console.log('err:' + decodeURIComponent(resp.data)) // for debug
}
// TODO: 需要依據(jù)后端實(shí)際情況判斷
return Promise.reject(error)
}
)
2. 點(diǎn)擊導(dǎo)出按鈕,請(qǐng)求api. 需要注意的是接口請(qǐng)求配置的響應(yīng)類型responseType:'blob' (也可以是配置arrayBuffer) ; 然IE9及以下瀏覽器不支持createObjectURL. 需要特別處理下IE瀏覽器將blob轉(zhuǎn)換成文件。
exportExcel () {
let params = {}
let p = this.getQueryParams() // 獲取相應(yīng)的參數(shù)
if (p) params = Object({}, params, p)
axios
.get('接口地址', {
params: params,
responseType: 'blob'
})
.then(res => {
var blob = new Blob([res.data], {
type: 'application/vnd.ms-excel;charset=utf-8'
})
// 針對(duì)于IE瀏覽器的處理, 因部分IE瀏覽器不支持createObjectURL
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, res.fileName)
} else {
var downloadElement = document.createElement('a')
var href = window.URL.createObjectURL(blob) // 創(chuàng)建下載的鏈接
downloadElement.href = href
downloadElement.download = res.fileName // 下載后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 點(diǎn)擊下載
document.body.removeChild(downloadElement) // 下載完成移除元素
window.URL.revokeObjectURL(href) // 釋放掉blob對(duì)象
}
})
}
三、WebApi + NPOI 后端處理
1. 需要通過接口參數(shù),查詢數(shù)據(jù)
為了保持與分頁組件查詢接口一直的參數(shù),采用了get請(qǐng)求方式,方便前端傳參。webapi接口必須返回IHttpActionResult 類型
[HttpGet]
public IHttpActionResult ExportData([FromUri]Pagination pagination, [FromUri] OrderReqDto dto)
{
//取出數(shù)據(jù)源
DataTable dt = this.Service.GetMemberPageList(pagination, dto.ConvertToFilter());
if (dt.Rows.Count > 65535)
{
throw new Exception("最大導(dǎo)出行數(shù)為65535行,請(qǐng)按條件篩選數(shù)據(jù)!");
}
foreach (DataRow row in dt.Rows)
{
var isRealName = row["IsRealName"].ToBool();
row["IsRealName"] = isRealName ? "是" : "否";
}
var model = new ExportModel();
model.Data = JsonConvert.SerializeObject(dt);
model.FileName = "會(huì)員信息";
model.Title = model.FileName;
model.LstCol = new List<ExportDataColumn>();
model.LstCol.Add(new ExportDataColumn() { prop = "FullName", label = "會(huì)員名稱" });
model.LstCol.Add(new ExportDataColumn() { prop = "RealName", label = "真實(shí)姓名" });
model.LstCol.Add(new ExportDataColumn() { prop = "GradeName", label = "會(huì)員等級(jí)" });
model.LstCol.Add(new ExportDataColumn() { prop = "Telphone", label = "電話" });
model.LstCol.Add(new ExportDataColumn() { prop = "AreaName", label = "區(qū)域" });
model.LstCol.Add(new ExportDataColumn() { prop = "GridName", label = "網(wǎng)格" });
model.LstCol.Add(new ExportDataColumn() { prop = "Address", label = "門牌號(hào)" });
model.LstCol.Add(new ExportDataColumn() { prop = "RegTime", label = "注冊時(shí)間" });
model.LstCol.Add(new ExportDataColumn() { prop = "Description", label = "備注" });
return ExportDataByFore(model);
}
2.關(guān)鍵導(dǎo)出函數(shù) ExportDataByFore的實(shí)現(xiàn)
[HttpGet]
public IHttpActionResult ExportDataByFore(ExportModel dto)
{
var dt = JsonConvert.DeserializeObject<DataTable>(dto.Data);
var fileName = dto.FileName + DateTime.Now.ToString("yyMMddHHmmssfff") + ".xls";
//設(shè)置導(dǎo)出格式
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.Title = dto.Title;
excelconfig.TitleFont = "微軟雅黑";
excelconfig.TitlePoint = 25;
excelconfig.FileName = fileName;
excelconfig.IsAllSizeColumn = true;
//每一列的設(shè)置,沒有設(shè)置的列信息,系統(tǒng)將按datatable中的列名導(dǎo)出
excelconfig.ColumnEntity = new List<ColumnEntity>();
//表頭
foreach (var col in dto.LstCol)
{
excelconfig.ColumnEntity.Add(new ColumnEntity() { Column = col.prop, ExcelColumn = col.label });
}
//調(diào)用導(dǎo)出方法
var stream = ExcelHelper.ExportMemoryStream(dt, excelconfig); // 通過NPOI形成將數(shù)據(jù)繪制成Excel文件并形成內(nèi)存流
var browser = String.Empty;
if (HttpContext.Current.Request.UserAgent != null)
{
browser = HttpContext.Current.Request.UserAgent.ToUpper();
}
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(stream);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // 返回類型必須為文件流 application/octet-stream
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") // 設(shè)置頭部其他內(nèi)容特性, 文件名
{
FileName =
browser.Contains("FIREFOX")
? fileName
: HttpUtility.UrlEncode(fileName)
};
return ResponseMessage(httpResponseMessage);
}
3. web api 的CORS配置
采用web api 構(gòu)建后端接口服務(wù)的同學(xué),都知道,接口要解決跨域問題,都需要進(jìn)行api的 CORS配置, 這里主要是針對(duì)于前端axios的響應(yīng)response header中獲取不到 content-disposition屬性,進(jìn)行以下配置

四、總結(jié)
以上就是我在實(shí)現(xiàn)axios導(dǎo)出Excel文件功能時(shí),遇到的一些問題,以及關(guān)鍵點(diǎn)進(jìn)行總結(jié)。因?yàn)轫?xiàng)目涉及到前后端其他業(yè)務(wù)以及公司架構(gòu)的一些核心源碼。要抽離一個(gè)完整的demo,比較耗時(shí),所以沒有完整demo展示. 但我已把NPOI相關(guān)的操作函數(shù)源碼,整理放至github上。https://github.com/yinboxie/BlogExampleDemo
相關(guān)文章
基于Ant-design-vue的Modal彈窗 封裝 命令式與Hooks用法
這篇文章主要給大家介紹了基于Ant-design-vue的Modal彈窗封裝命令式與Hooks用法,文中有詳細(xì)的代碼示例,具有一定的參考價(jià)值,感興趣的同學(xué)可以借鑒閱讀2023-06-06

