The example in this article mainly describes the method of generating CSV files in Java. The specific implementation steps are as follows:
1. Create a new CSVUtils.java file:
package com.saicfc.pmpf.internal.manage.utils;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java .io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.URLEncoder;import java.util.ArrayList;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.List;import java .util.Map;import javax.servlet.http.HttpServletResponse;import org.apache.commons.beanutils.BeanUtils;/** * File operations*/public class CSVUtils { /** * Generate as CVS file* @param exportData * Source data List * @param map * List header map of csv file * @param outPutPath * File path * @param fileName * File name * @return */ @SuppressWarnings("rawtypes") public static File createCSVFile(List exportData, LinkedHashMap map, String outPutPath, String fileName) { File csvFile = null; BufferedWriter csvFileOutputStream = null; try { File file = new File(outPutPath); if (!file.exists()) { file.mkdir( ); } //Define the file name format and create csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath)); System.out.println("csvFile: " + csvFile); // UTF-8 enables correct reading of the delimiter "," csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream (csvFile), "UTF-8"), 1024); System.out.println("csvFileOutputStream: " + csvFileOutputStream); // Write the file header for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext();) { java.util.Map. Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next(); csvFileOutputStream .write(""" + (String) propertyEntry.getValue() != null ? (String) propertyEntry .getValue() : "" + """); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } csvFileOutputStream.newLine(); //Write file content for (Iterator iterator = exportData.iterator(); iterator.hasNext();) { Object row = (Object) iterator.next(); for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator .hasNext();) { java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator .next(); csvFileOutputStream.write((String) BeanUtils.getProperty(row, (String) propertyEntry.getKey())); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } if (iterator.hasNext()) { csvFileOutputStream.newLine( ); } } csvFileOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { csvFileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return csvFile; } /** * Download file * @param response * @param csvFilePath * File path * @param fileName * File name * @throws IOException */ public static void exportFile(HttpServletResponse response, String csvFilePath, 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(csvFilePath); 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) { System.out.println(e); } finally { if (in != null) { try { in.close() ; } catch (Exception e) { throw new RuntimeException(e); } } } } /** * Delete all files under filePath in this directory * @param filePath * File directory path*/ public static void deleteFiles(String filePath) { File file = new File(filePath); if (file.exists()) { File[] files = file.listFiles(); for (int i = 0 ; i < files.length; i++) { if (files[i].isFile()) { files[i].delete(); } } } } /** * Delete a single file* @param filePath * file directory path * @param fileName * file name */ public static void deleteFile(String filePath, String fileName) { File file = new File(filePath); if (file.exists()) { File[] files = file .listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { if (files[i].getName().equals(fileName)) { files[i].delete(); return; } } } } } /** * Test data* @param args */ @SuppressWarnings({ "rawtypes ", "unchecked" }) public static void main(String[] args) { List exportData = new ArrayList<Map>(); Map row1 = new LinkedHashMap<String, String>(); row1.put("1", "11"); row1.put("2", "12"); row1.put("3", "13"); row1. put("4", "14"); exportData.add(row1); row1 = new LinkedHashMap<String, String>(); row1.put("1", "21"); row1.put("2", "22"); row1.put("3", "23"); row1.put("4", "24"); exportData.add(row1); LinkedHashMap map = new LinkedHashMap(); map.put("1", "First column"); map.put("2", "Second column"); map.put("3", "Third column"); map.put("4", "Fourth column"); String path = "c:/export/"; String fileName = "File export"; File file = CSVUtils.createCSVFile(exportData, map, path, fileName); String fileName2 = file.getName(); System.out.println("File name: " + fileName2); }}
2. Call the createCSVFile method to generate a CSV file
String name = "Bank refund data";List exportData = new ArrayList();LinkedHashMap datamMap = null;for (Iterator iterator = refundList.iterator(); iterator.hasNext();) { HashMap map = (HashMap) iterator. next(); datamMap = new LinkedHashMap(); datamMap.put("1", map.get("merOrderId")); datamMap.put("2",DateUtil.convertDateToString("yyyyMMdd", (Date) map.get("orderTime"))); BigDecimal amount = (BigDecimal) map.get( "amount"); String amountString = amount.divide(new BigDecimal(10)).toPlainString(); datamMap.put("3", amountString); datamMap.put("4", map.get("remark") != null ? map.get("remark") : ""); exportData.add(datamMap) ;} LinkedHashMap map = new LinkedHashMap(); map.put("1", "Order Number"); map.put("2", "Payment Date"); map.put("3", "Return cash amount (integer unit: cents)"); map.put("4", "Reason for return"); File file = CSVUtils.createCSVFile(exportData, map, filePath, name );//Generate CSV file fileName = file.getName(); CSVUtils.exportFile(response, filePath + fileName, fileName);//Download the generated CSV file