最近在使用easyexcel的时候,碰到一个小坑:
在使用Safari
浏览器进行导出的时候,导出的文件会自动增加一个.xlw
后缀。
解决办法
将原来的代码:
response.setContentType("application/vnd.ms-excel");
|
改成:
response.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
然后所有浏览器都没有问题了。
附上easyexcel导出的工具类
public class ExcelUtil {
private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
public static void export(List<? extends BaseRowModel> list, String excelName, HttpServletResponse response, Class<? extends BaseRowModel> clazz) {
ServletOutputStream out = null; ExcelWriter writer = null; try { out = response.getOutputStream(); writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true); String fileName = excelName + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
Sheet sheet2 = new Sheet(2, 3, clazz, "sheet", null); writer.write(list, sheet2); response.setCharacterEncoding("utf-8");
response.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
setFileDownloadHeader(response, fileName);
out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != writer) { writer.finish(); } if (null != out) { try { out.flush(); } catch (IOException e) { logger.error("excel导出出错", e); } } } }
private static void setFileDownloadHeader( HttpServletResponse response, String filename) { String headerValue = "attachment;"; headerValue += " filename=\"" + encodeURIComponent(filename) + "\";"; headerValue += " filename*=utf-8''" + encodeURIComponent(filename + ".xlsx"); response.setHeader("Content-Disposition", headerValue); }
private static String encodeURIComponent(String value) { try { return URLEncoder.encode(value, "UTF-8") .replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }
|