1. 程式人生 > 其它 >實現檔案匯出功能程式碼記錄

實現檔案匯出功能程式碼記錄

要實現檔案匯出功能,若Controller程式碼如下:

@RequestMapping(value = "/exportCustomerList", method = RequestMethod.POST)
public void exportCustomerList(@RequestBody CustomerBase customerBase, HttpServletResponse response) {
    XSSFWorkbook workbook = customerBaseService.genCustomerListExcel(customerBase);

    try {
        response.setHeader(
"content-Disposition", "attachment;filename=" + URLEncoder.encode("客戶基礎資訊.xlsx", "utf-8")); OutputStream outputStream = response.getOutputStream(); workbook.write(outputStream); outputStream.flush(); outputStream.close(); } catch (IOException e) {
throw new ServiceException("excel寫入失敗"); } }

則對應的前端匯出程式碼如下:

const exportFile = () => {
  return new Promise((resolve, reject) => {
    const param = Object.assign({}, formState);
    CustomerBaseApi.exportCustomerList(param)
      .then((response) => {
        const data = response.data;
        
if (data.size === 0) { message.error("沒有匯出資料"); return; } const url = window.URL.createObjectURL(data); const link = document.createElement("a"); link.style.display = "none"; link.href = url; link.setAttribute("download", "客情基礎資訊.xls"); document.body.appendChild(link); link.click(); }) .catch((error) => { if (error.message !== "") { message.error(error.message); } reject(error); }); }); };

介面請求程式碼為:

exportCustomerList(data) {
  return request({
    url: "/customerbase/exportCustomerList",
    method: "post",
    data,
    responseType: 'blob',
    headers: { 'content-type': 'application/x-download;charset=utf-8' }
  });
}