项目要求导出csv格式的文本,特此记录一下,中间还是遇到了不少的问题
在Java中,你可以使用不同的库来导出CSV格式的文件。我将向你展示一个简单的例子,使用纯Java和字符串操作来创建CSV文件。但是,请注意,对于大型数据集,使用专门的CSV库(如Apache Commons CSV或OpenCSV)会更有效。
import java.io.FileWriter; import java.io.IOException; public class CsvExporter { public static void main(String[] args) { String csvFile = "path/to/your/file.csv"; FileWriter writer = null; try { writer = new FileWriter(csvFile); // 写入标题行 String header = "Column1,Column2,Column3"; writer.append(header); writer.append('\n'); // 写入一些数据 String data1 = "Data1"; String data2 = "Data2"; String data3 = "Data3"; String line = data1 + "," + data2 + "," + data3; writer.append(line); writer.append('\n'); // 这只是一个例子,你可以根据需要添加更多数据 System.out.println("CSV file was created successfully !!!"); } catch (Exception e) { System.out.println("Error in CsvFileWriter..."); e.printStackTrace(); } finally { try { writer.flush(); writer.close(); } catch (IOException e) { System.out.println("Error while flushing/closing writer..."); e.printStackTrace(); } } } }
如何使用POI
List<List<Object>> dataList=new ArrayList<>(); for (TestEntitytestEntity: addTest) { List<Object> data= new ArrayList<>(); data.add(testEntity.getName()); data.add(testEntity.getUserid()); if (stringListMap.size()>0){ data.add(stringListMap.get(testEntity.getOwOpenid()).getPhone()); data.add(stringListMap.get(testEntity.getOwOpenid()).getNickName()); } dataList.add(data); } // poi导出csv List<Object> headList=new ArrayList<>(); headList.add("name"); headList.add("userId"); headList.add("phone"); headList.add("nickname"); Date date = new Date(); String format = new SimpleDateFormat("yyyy-mm-dd").format(date); String hh = new SimpleDateFormat("HH").format(date); String fileName=format+"快照数据"+hh; CSVUtil.createCSVFile(response,headList,dataList,fileName);
CSV文件导出工具类
package com.zkys.product.common.utils; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.List; /** * * CSV文件导出工具类 * * @author qixin * @description TODO * @data 2018/7/10 19:25 * Version 1.0 */ public class CSVUtil{ /** * CSV文件生成方法 * @param * @param head * @param dataList * @param filename */ public static void createCSVFile(HttpServletResponse response, List<Object> head, List<List<Object>> dataList, String filename) { File csvFile = null; BufferedWriter csvWtriter = null; InputStream in = null; OutputStream out = null; try { csvFile=new File("./"+filename+".csv"); // GB2312使正确读取分隔符"," csvWtriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( csvFile), "GBK"), 1024); // 写入文件头部 writeRow(head, csvWtriter); // 写入文件内容 for (List<Object> row : dataList) { writeRow(row, csvWtriter); } csvWtriter.flush(); in = new FileInputStream(csvFile); int len = 0; byte[] buffer = new byte[1024*1024*5]; out = response.getOutputStream(); response.reset(); // 设置此response为文件下载响应 response.setContentType("application/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(csvFile.getName(), "UTF-8")); response.setCharacterEncoding("UTF-8"); // 先写UTF-8文件标志头 out.write(new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (csvFile != null) { csvFile.delete(); } if (csvWtriter != null) { csvWtriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 写一行数据方法 * @param row * @param csvWriter * @throws IOException */ private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException { // 写入文件头部 for (Object data : row) { StringBuffer sb = new StringBuffer(); String rowStr = sb.append("\"").append(data).append("\",").toString(); csvWriter.write(rowStr); } csvWriter.newLine(); } }