java springboot api接口导出xlsx(不使用easyexcle)
说明
在上一个文章里说了,用了阿里巴巴的easyexcle会导致项目build后的jar包体积增大20MB左右,所以想了个曲线救国的方式
其中的\t是制表符,即tab键,\n是回车
你可以自己试着这样写个txt文件,然后改后缀为xlsx,用WPS和OFFICE也是可以打开的
只不过没有花里胡哨的格式而已,不过,无伤大雅
工具类
/**
* 导出卡密为XLSX
* @param request
* @param response
* @param fileName
* @param list
*/
public static void exportCard2Xls(HttpServletRequest request, HttpServletResponse response, String fileName, List<Card> list) {
request.getSession();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
try {
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//如果用这种方式导出,WPS或者office打开文件时会检测到是SYLK,即此文件是一个文本文件
//这样没啥问题,但是如果第一个字符是"ID",就会有弹窗警告提示,如果用小写的"id"或者其他字符就不会再有弹窗提示
String ret = "id\t卡密\t点数\t秒数\t生成时间\t使用时间\t使用人账号\t卡密状态\t所属软件";
for (Card card : list) {
ret = ret + "\n" + card.getId() + "\t" + card.getCkey() + "\t" + card.getPoint() + "\t" + card.getSeconds() + "\t" +MyUtils.dateToStr(card.getAddTimeName())+ "\t" +MyUtils.dateToStr(card.getLetTimeName()) + "\t" + card.getLetUser() + "\t" + card.getStatusName() + "\t" + card.getFromSoftName();
}
OutputStream outputStream = null;
try {
outputStream = response.getOutputStream();
outputStream.write(ret.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return;
}

浙公网安备 33010602011771号