/**
* @author BNTang
*/
public class CsvUtils {
private CsvUtils() {
}
/**
* 导出csv文件
*
* @param response response
* @param fileName 文件名
* @param fileHeader 表头
* @param content 内容
*/
public static void write(HttpServletResponse response, String fileName, final String[] fileHeader, List<List<String>> content) {
try (OutputStream outputStream = getOutputStream(fileName, response);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(Objects.requireNonNull(outputStream), "GBK")) {
CSVPrinter csvPrinter = new CSVPrinter(outputStreamWriter, CSVFormat.DEFAULT.withHeader(fileHeader));
for (List<String> element : content) {
csvPrinter.printRecord(element);
}
csvPrinter.flush();
csvPrinter.close();
} catch (IOException e) {
log.error("CSV文件写入失败");
}
log.info("CSV文件写入成功");
}
/**
* 导出文件时为Writer生成OutputStream
*
* @param fileName 文件名
* @param response {@link HttpServletResponse}
* @return 输出流
*/
private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
return response.getOutputStream();
} catch (Exception e) {
log.error("导出失败");
}
return null;
}
}
write 方法中的 fileHeader
内容如下所示
/**
* 导出的CSV文件表头
*/
private static final String[] IN_STOCK_CSV_HEAD = {
"入库单号",
"单据状态",
"入库类型",
"关联单号",
"收货仓库",
"目的仓库",
"供应商名称",
"预计到仓日(国内)",
"实际到仓日(国内)",
"实际入库日(国内)",
"预计装柜日",
"生成上架单",
"入库单创建时间",
"SKU",
"产品名称",
"小组名称",
"库区",
"应收数量",
"已入库数(正品)",
"已入库数(坏品)",
"入库体积(立方米)"
};