1. 导出文件工具类
@Slf4j
public class ExportUtil {
/** CSV文件列分隔符 */
private static final String CSV_COLUMN_SEPARATOR = ",";
/** CSV文件列分隔符 */
private static final String CSV_RN = "\r\n";
/**
*
* @param dataList 集合数据
* @param colNames 表头部数据
* @param mapKey 查找的对应数据
* @param os 返回结果
*/
public static boolean doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) {
try {
StringBuffer buf = new StringBuffer();
String[] colNamesArr = null;
String[] mapKeyArr = null;
colNamesArr = colNames.split(",");
mapKeyArr = mapKey.split(",");
// 完成数据csv文件的封装
// 输出列头
for (String aColNamesArr : colNamesArr) {
buf.append(aColNamesArr).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
if (null != dataList) { // 输出数据
for (Map<String, Object> aDataList : dataList) {
for (String aMapKeyArr : mapKeyArr) {
buf.append(aDataList.get(aMapKeyArr)).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
}
}
// 写出响应
os.write(buf.toString().getBytes("GBK"));
os.flush();
return true;
} catch (Exception e) {
log.error("doExport错误...", e);
}
return false;
}
/**
* setHeader
*/
public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
// 设置文件后缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = fileName + sdf.format(new Date()) + ".csv";
// 读取字符编码
String utf = "UTF-8";
// 设置响应
response.setContentType("application/ms-txt.numberformat:@");
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
}
}
2.Controller接口
@RestController
@RequestMapping("/test")
@Slf4j
public class DownloadFileController {
@Autowired
private SysLogService sysLogService;
@GetMapping("/file")
public Result download(HttpServletResponse response) {
List<Map<String, Object>> dataList = null;
List<SysLog> logList = sysLogService.findAll();// 查询到要导出的信息
if (logList.size() == 0) {
ResultUtil.failure("无数据导出");
}
String sTitle = "id,用户名,操作类型,操作方法,创建时间";
String fName = "log_";
String mapKey = "id,username,operation,method,createDate";
dataList = new ArrayList<>();
Map<String, Object> map = null;
for (SysLog order : logList) {
map = new HashMap<>();
map.put("id", order.getId());
map.put("username", order.getUsername());
map.put("operation", order.getOperation());
map.put("method", order.getMethod());
map.put("createDate", DateFormatUtils.format(order.getCreateDate(), "yyyy/MM/dd HH:mm"));
dataList.add(map);
}
try (final OutputStream os = response.getOutputStream()) {
ExportUtil.responseSetProperties(fName, response);
ExportUtil.doExport(dataList, sTitle, mapKey, os);
return null;
} catch (Exception e) {
log.error("生成csv文件失败", e);
}
return ResultUtil.failure("数据导出出错");
}
}
3.测试
浏览器直接请求,可看到文件下载,Excel可直接打开文件。