前後端分離,後端返回文件流,在前端通過請求 api 的方式下載 excel 文件。
前端代碼
- 適用於 v4,應該也適用於 v2.3.1,在 v4 版本下測試通過,如果用的是 v2.3.0,請看最後面的修改方式。
- 另外,剛用 TypeScript,因爲還不是很熟,有些地方還不符合 TypeScript 的編碼規範,先將就看~~
export function excelDownload(url, options) {
let tokenSessionStorage: string | null = sessionStorage.getItem('token');
let excelFileName : string | null = options.body.excelFileName;
options = { credentials: 'include', ...options };
options.body = JSON.stringify({
method: url,
jsonStringParameter: JSON.stringify(options.body),
});
options.headers = {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
Authorization: tokenSessionStorage,
...options.headers,
};
fetch(url, options)
.then(response => response.blob())
.then(blobData => {
download(blobData, excelFileName);
});
}
function download(blobData: Blob, forDownLoadFileName: string | null): any {
const aLink = document.createElement('a');
document.body.appendChild(aLink);
aLink.style.display = 'none';
aLink.href = window.URL.createObjectURL(blobData);
aLink.setAttribute('download', forDownLoadFileName);
aLink.click();
document.body.removeChild(aLink);
}
遇到的坑
前端提交請求的參數體,用的是 options.data,參照了登錄的 api 請求方法,在文件 src\services\login.ts
中定義。
export async function fakeAccountLogin(params: LoginParamsType) {
return request('/api/auth/login', {
method: 'POST',
data: params,
});
}
我的方法是:
export async function exportToExcelCollectionDetail(params) {
return excelDownload('/api/exportToExcel/collectionDetail', {
method: 'POST',
data: params,
});
}
調用前將 data 轉換成 json 數據:
options.data = JSON.stringify({
method: url,
jsonStringParameter: JSON.stringify(options.data),
});
在後端,只有 method 有值,jsonStringParameter 被“吞”掉了,就象沒有傳這個參數一樣,所以,得到的值是 null。
各種查資料,後來在 fetch 的 github 項目看到,Post JSON,請求的參數用的是 body,代碼如下:
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
於是,將 options.data 改爲 options.body:
options.body = JSON.stringify({
method: url,
jsonStringParameter: JSON.stringify(options.body),
});
記得調用方也要改:
export async function exportToExcelCollectionDetail(params) {
return excelDownload('/api/exportToExcel/collectionDetail', {
method: 'POST',
body: params,
});
}
竟然就可以了!
在查詢數據,以及登錄功能,都用的是關鍵字 data,能正常傳遞參數,不過,調用的是 umi-request 封裝過的 fetch,umi-request 對參數的定義是:
export interface RequestOptionsInit extends RequestInit {
charset?: 'utf8' | 'gbk';
requestType?: 'json' | 'form';
data?: any;
params?: object;
responseType?: ResponseType;
useCache?: boolean;
ttl?: number;
timeout?: number;
errorHandler?: (error: ResponseError) => void;
prefix?: string;
suffix?: string;
throwErrIfParseFail?: boolean;
parseResponse?: boolean;
cancelToken?: CancelToken;
}
後端導出 excel 文件的代碼片斷
// 設置response頭信息
response.reset();
response.setContentType("application/x-download;charset=UTF-8");
try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelFileName, "UTF-8") + ".xls");
//創建一個WorkBook,對應一個Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//在Workbook中,創建一個sheet,對應Excel中的工作薄(sheet)
HSSFSheet sheet = wb.createSheet(excelFileName);
HSSFCellStyle headerStyle = getStyleHeader(wb);
// 填充工作表
// some code
//將文件輸出
OutputStream outputStream = response.getOutputStream();
wb.write(outputStream);
outputStream.flush();
outputStream.close();
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
ant design pro v2.3.0 版本,導出 excel
修改 src\utils\request.js
,在以下代碼的 return 之前:
return (
fetch(url, newOptions)
.then(checkStatus)
//.then(response => cachedSave(response, hashcode))
.then(response => {
// codes
添加以下代碼:
if (url.includes('exportToExcel')) {
const { excelFileName } = options.body;
return fetch(url, newOptions)
.then(response => response.blob())
.then(blobData => {
download(blobData, excelFileName);
});
}
前提是,下載 excel 的 api 路徑都要添加 exportToExcel
。
其中,download 方法在 v2 與 v4 通用,請參照 v4 的代碼。
對 newOptions 的處理,在 if (!(newOptions.body instanceof FormData)) {
下添加:
newOptions.headers = {
Authorization: token,
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
...newOptions.headers,
};
newOptions.body = JSON.stringify({
method: url,
jsonStringParameter: JSON.stringify(newOptions.body),
});