Java IDEA controller导出CSV,excel
Java IDEA controller导出CSV,excel
- 导出excel/csv,亲测可共用一个方法,代码逻辑里判断设置不同的表头及contentType;
- 导出excel
- 导出csv
- 优化:有数据时才可以导出
- 参考
导出excel/csv,亲测可共用一个方法,代码逻辑里判断设置不同的表头及contentType;
导出excel
eg:xls
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("导出表.xlsx", "utf-8"));
导出csv
eg:csv
response.setContentType("application/csv");
response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode("export.csv", "UTF-8"));
ServletOutputStream out = response.getOutputStream();
out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
out.write(st.toString.getBytes("UTF-8"));
优化:有数据时才可以导出
当没有数据时提示无法导出,因此返回提示信息,ResponseMessage
在有数据可以正常到导出时可能会报错:Cannot call sendError() after the response has been committed。
在最后返回null 可成功解决,可参考
参考
- https://blog.csdn.net/missingshirely/article/details/132339295
- https://blog.csdn.net/weixin_56567361/article/details/126640185