//platform 为前端传入的,用于判断不同操作系统下的换行符
protected String getNewLine(String platform) {
if (StringUtils.equals(platform, "MacIntel")) {
return "\n";
} else if (StringUtils.equals(platform, "Macintosh") || StringUtils.equals(platform, "Mac68K")) {
return "\r";
} else if (StringUtils.startsWith(platform, "Linux")) {
return "\n";
} else if (StringUtils.equals(platform, "Windows") ||
StringUtils.equals(platform, "Win16") ||
StringUtils.equals(platform, "Win32") ||
StringUtils.equals(platform, "WinCE")) {
return "\r\n";
}
throw new NoteException("无法确定该系统使用的换行符.");
}
@RequestMapping(value = "/export", method = RequestMethod.GET)
public void export(HttpServletResponse response, String platform, String startTime, String endTime, String title) {
String newLine = getNewLine(platform);
long now = System.currentTimeMillis();
if (null != startTime) {
if (Long.parseLong(startTime) > now) {
throw new NoteException("筛选的开始时间不可超过当前时间.");
}
}
List<LaitoonOrderView> list = courseMapper.totalList(startTime, endTime, title, null, null);
if (null == list || list.isEmpty()) {
throw new NoteException("导出的数据为空.");
}
StringBuilder elems = new StringBuilder();
//excel 头部信息
elems.append("日期").append(",")
.append("收益金额").append(",")
.append("购买笔数").append(",")
.append("购买人数").append(",")
.append(newLine);
//excel 内容
for (LaitoonOrderView e : list) {
elems.append(e.getTimeDisplay()).append(",")
.append(e.getNeedPay()).append(",")
.append(e.getBuyNum()).append(",")
.append(e.getBuyPeople()).append(",")
.append(newLine);
}
//方法一
byte[] bytes;
if (null != isOffice && isOffice) {
//导出文件以wps的方式打开
bytes = elems.toString().getBytes(StandardCharsets.UTF_8);
} else {
//导出文件以Microsoft excel的方式打开
bytes = elems.toString().getBytes(Charset.forName("GB2312"));
}
// gc
list = null;
elems = null;
OutputStream out = null;
try {
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=export-" + System.currentTimeMillis() + ".csv");
response.setContentType("application/octet-stream");
// 处理文件 返回流
out = response.getOutputStream();
//方法二
//让response 告诉Excel,此CSV文件的编码为UTF-8
// out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
out.write(bytes);
out.flush();
} catch (Exception e) {
throw new NoteException(e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}