/**
* 根据sql导成csv;成功返回文件流,失败返回错误信息
* @param sql 导出sql
* @param col 字段信息,以逗号分隔
* @param title 文件头信息,以逗号分隔
* @param separator csv文件的分隔符
* @param baseServiceName
* @param request
* @param response
*/
@RequestMapping("exportForCsvStream")
@ResponseBody
public R<String> exportForCsvStream(String sql, String col, String title, String separator, String fileName, String baseServiceName, HttpServletRequest request, HttpServletResponse response) {
logger.info("sql={},title={},separator={},fileName={},baseServiceName={}", sql, title, separator, fileName, baseServiceName);
try {
if (StringUtils.isBlank(separator)) {
separator = ",";
}
if (StringUtils.isBlank(fileName)) {
fileName = "data.csv";
}
setResponse(fileName, request, response);
OutputStream os = new BufferedOutputStream(response.getOutputStream(), BUFFER_SIZE);
//调用service把文件写入到输出流,请自行实现
this.getBaseService(baseServiceName).exportForCsv(os, sql, col, title, separator);
os.close();
return null;
} catch(Exception e) {
e.printStackTrace();
response.reset();
response.setContentType("application/json");
response.setHeader("Content-Disposition", "");
return R.error(-1, "发生异常");
}
}
private void setResponse(String fileName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String urlFileName = "";
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
urlFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
} else {
urlFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
}
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + urlFileName + "\"");
response.setHeader("Connection", "close");
}