1、前言
項目中前端採用的Element UI 框架, 遠程數據請求,使用的是axios,後端接口框架採用的asp.net webapi,數據導出成Excel採用NPOI組件。其業務場景,主要是列表頁(如會員信息,訂單信息等)表格數據導出,如表格數據進行了條件篩選,則須要將條件傳至後端api,篩選數據後,導出成Excel。 前端
思考過前端導出的3種方案: ios
1.使用location.href 打開接口地址.缺點: 不能傳token至後端api, 沒法保證接口的安全性校驗,而且接口只能是get方式請求. git
2.採用axios請求接口,先在篩選後的數據服務端生成文件並保存,而後返回遠程文件地址,再採用 location.href打開文件地址進行下載. 缺點: 實現複雜,而且每次導出會在服務端生成文件,可是又沒有合適的時機再次觸發刪除文件,會在服務端造成垃圾數據。優勢:每次導出均可以有記錄。 github
3. 採用axios請求接口,服務端api返回文件流,前端接收到文件流後,採用blob對象存儲,並建立成url, 使用a標籤下載. 優勢:前端可傳token參數校驗接口安全性,並支持get或post兩種方式。 web
因其應用場景是導出Excel文件以前,必須篩選數據,並須要對接口安全進行校驗,因此第3種方案爲最佳選擇。在百度以後,發現目前使用最多的也是第3種方案。 axios
2、Vue + axios 前端處理
1.axios 需在response攔截器裏進行相應的處理(這裏再也不介紹axios的使用, 關於axios的用法,具體請查看Axios中文說明 ,咱們在項目中對axios進行了統一的攔截定義). 需特別注意: response.headers['content-disposition'],默認是獲取不到的,須要對服務端webapi進行配置,請查看第三點中webapi CORS配置 後端
-
// respone攔截器
-
service.interceptors.response.use(
-
response => {
-
// blob類型爲文件下載對象,不管是什麼請求方式,直接返回文件流數據
-
if (response.config.responseType === 'blob') {
-
const fileName = decodeURI(
-
response.headers['content-disposition'].split('filename=')[1]
-
)
-
// 返回文件流內容,以及獲取文件名, response.headers['content-disposition']的獲取, 默認是獲取不到的,須要對服務端webapi進行配置
-
return Promise.resolve({ data: response.data, fileName: fileName })
-
}
-
// 依據後端邏輯實際狀況,須要彈窗展現友好錯誤
-
},
-
error => {
-
let resp = error.response
-
if (resp.data) {
-
console.log('err:' + decodeURIComponent(resp.data)) // for debug
-
}
-
// TODO: 須要依據後端實際狀況判斷
-
return Promise.reject(error)
-
}
-
)
2. 點擊導出按鈕,請求api. 須要注意的是接口請求配置的響應類型responseType:'blob' (也能夠是配置arrayBuffer) ; 然IE9及如下瀏覽器不支持createObjectURL. 須要特別處理下IE瀏覽器將blob轉換成文件。 api
-
exportExcel () {
-
let params = {}
-
let p = this.getQueryParams() // 獲取相應的參數
-
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'
-
})
-
// 針對於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) // 建立下載的連接
-
downloadElement.href = href
-
downloadElement.download = res.fileName // 下載後文件名
-
document.body.appendChild(downloadElement)
-
downloadElement.click() // 點擊下載
-
document.body.removeChild(downloadElement) // 下載完成移除元素
-
window.URL.revokeObjectURL(href) // 釋放掉blob對象
-
}
-
})
-
}
3、WebApi + NPOI 後端處理
1. 須要經過接口參數,查詢數據 跨域
爲了保持與分頁組件查詢接口一直的參數,採用了get請求方式,方便前端傳參。webapi接口必須返回IHttpActionResult 類型 瀏覽器
-
[HttpGet]
-
public IHttpActionResult ExportData([FromUri]Pagination pagination, [FromUri] OrderReqDto dto)
-
{
-
//取出數據源
-
DataTable dt = this.Service.GetMemberPageList(pagination, dto.ConvertToFilter());
-
if (dt.Rows.Count > 65535)
-
{
-
throw new Exception("最大導出行數爲65535行,請按條件篩選數據!");
-
}
-
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 = "會員信息";
-
model.Title = model.FileName;
-
model.LstCol = new List<ExportDataColumn>();
-
model.LstCol.Add(new ExportDataColumn() { prop = "FullName", label = "會員名稱" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "RealName", label = "真實姓名" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "GradeName", label = "會員等級" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "Telphone", label = "電話" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "AreaName", label = "區域" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "GridName", label = "網格" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "Address", label = "門牌號" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "RegTime", label = "註冊時間" });
-
model.LstCol.Add(new ExportDataColumn() { prop = "Description", label = "備註" });
-
return ExportDataByFore(model);
-
}
2.關鍵導出函數 ExportDataByFore的實現
-
[HttpGet]
-
public IHttpActionResult ExportDataByFore(ExportModel dto)
-
{
-
var dt = JsonConvert.DeserializeObject<DataTable>(dto.Data);
-
var fileName = dto.FileName + DateTime.Now.ToString("yyMMddHHmmssfff") + ".xls";
-
//設置導出格式
-
ExcelConfig excelconfig = new ExcelConfig();
-
excelconfig.Title = dto.Title;
-
excelconfig.TitleFont = "微軟雅黑";
-
excelconfig.TitlePoint = 25;
-
excelconfig.FileName = fileName;
-
excelconfig.IsAllSizeColumn = true;
-
//每一列的設置,沒有設置的列信息,系統將按datatable中的列名導出
-
excelconfig.ColumnEntity = new List<ColumnEntity>();
-
//表頭
-
foreach (var col in dto.LstCol)
-
{
-
excelconfig.ColumnEntity.Add(new ColumnEntity() { Column = col.prop, ExcelColumn = col.label });
-
}
-
//調用導出方法
-
var stream = ExcelHelper.ExportMemoryStream(dt, excelconfig); // 經過NPOI造成將數據繪製成Excel文件並造成內存流
-
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") // 設置頭部其餘內容特性, 文件名
-
{
-
FileName =
-
browser.Contains("FIREFOX")
-
? fileName
-
: HttpUtility.UrlEncode(fileName)
-
};
-
return ResponseMessage(httpResponseMessage);
-
}
3. web api 的CORS配置
採用web api 構建後端接口服務的同窗,都知道,接口要解決跨域問題,都須要進行api的 CORS配置, 這裏主要是針對於前端axios的響應response header中獲取不到 content-disposition屬性,進行如下配置
4、總結
以上就是我在實現axios導出Excel文件功能時,遇到的一些問題,以及關鍵點進行總結。由於項目涉及到先後端其餘業務以及公司架構的一些核心源碼。要抽離一個完整的demo,比較耗時,因此沒有完整demo展現. 但我已把NPOI相關的操做函數源碼,整理放至github上。https://github.com/yinboxie/BlogExampleDemo