1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| package com.nongfenqi.transport.common;
import com.nongfenqi.transport.export.LogisticsExport; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.text.DateFormat; import java.util.List;
/** * 导出工具类 */ @Service @Slf4j public class ExportUtil {
// csv 文件的标题行 private static String TITLE_LINE = "物流单编号" + "," + "发货单编号" + "," + "厂家名称" + "," + "发货基地" + "," + "品牌名称" + "," + "商品名称" + "," + "包装数 单位:袋" + "," + "重量 单位:吨" + "," + "收货人姓名" + "," + "收货地址" + "," + "紧急联系人1" + "," + "紧急联系人1手机号" + "," + "紧急联系人2" + "," + "紧急联系人2手机号" + ",";
/** * 创建一个 CSV 格式的临时文件 * * @param logisticsExports * @return * @throws IOException */ public static File createLogisticsCVSFile(List<LogisticsExport> logisticsExports) throws IOException { File tempFile = File.createTempFile(DateFormat.getDateTimeInstance().toString(), ".csv"); OutputStream out = new FileOutputStream(tempFile); BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile, true)); bw.write(TITLE_LINE); bw.newLine(); for (LogisticsExport logistics : logisticsExports) { bw.write(logistics.toString()); bw.newLine(); } bw.close(); return tempFile; }
/** * 导出 CSV 文件 * * @param response * @param file * @param fileName * @throws IOException */ public static void exportCSVFile(HttpServletResponse response, File file, String fileName) throws IOException { response.setContentType("application/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream in = null; try { in = new FileInputStream(file); int len = 0; byte[] buffer = new byte[1024]; response.setCharacterEncoding("UTF-8"); OutputStream out = response.getOutputStream(); while ((len = in.read(buffer)) > 0) { out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}); out.write(buffer, 0, len); } } catch (FileNotFoundException e) { log.warn(e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (Exception e) { throw new RuntimeException(e); } } } }
}
|