Java generated CSV file example details

  • 2020-04-01 03:25:23
  • OfStack

The example of this paper mainly describes the method of Java to generate CSV file, the specific implementation steps are as follows:

1. 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;


public class CSVUtils {

  
  @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 it
      csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));
      System.out.println("csvFile : " + csvFile);
      //Utf-8 causes the delimiter "," to be read correctly
      csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
        csvFile), "UTF-8"), 1024);
      System.out.println("csvFileOutputStream : " + csvFileOutputStream);
      //Write 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 contents
      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;
  }

  
  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);
        }
      }
    }
  }

  
  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();
        }
      }
    }
  }

  
  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;
          }
        }
      }
    }
  }

  
  @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", " The first column ");
    map.put("2", " The second column ");
    map.put("3", " The third column ");
    map.put("4", " The 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 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", " The order number ");
 map.put("2", " Date of payment ");
 map.put("3", " Return cash amount (round amount)   Unit: points) ");
 map.put("4", " The return reason ");
 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

Related articles: