解决导出excel表格无法打开的问题

前后端分离实现导出excel,后端使用easyexcel将数据写入excel表格,然后将其写入到响应流中,关于easyexcel的快速使用可参考文章:JAVA使用easyexcel导出excel

后端主要代码如下:

public  void exportExcel(HttpServletResponse response, List excelModel,
			String fileName) {
		try (OutputStream out = response.getOutputStream()) {
			ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
			if (!excelModel.isEmpty()) {
				Sheet sheet = new Sheet(1, 0, excelModel.get(0).getClass());

				fileName = URLEncoder.encode(fileName, "UTF-8");
				sheet.setSheetName(fileName);
				response.setCharacterEncoding("UTF-8");
				response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
				writer.write(excelModel, sheet);
			}
			writer.finish();
		} catch (Exception e) {
			throw new ApplicationException("导出excel错误", e);
		}
	}

上述代码中使用泛型使得导出excel代码更为通用。

前端逻辑代码使用typescript完成,代码示例如下:

function getFile(url: string, data: any, fileName: string): Promise {
    return new Promise((success, fail) =>  {
        handleRequest(get(url,
        {params: data,
            responseType: 'arraybuffer'},
        )).then(
        (res) => {
            const blob: Blob = new Blob([res.data]);
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(blob);
            downloadElement.href = href;
            downloadElement.download = fileName;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement);
            window.URL.revokeObjectURL(href);
            success('导出成功');
        }).catch((e) => {
            fail(e);
        });
    });
}

前端最关键的就是要设置responseType的值为blob或者arraybuffer,否则就会导致下载下来的excel表格无法打开.

你可能感兴趣的:(java,excel)