本文實例主要講述了Java產生CSV檔案的方法,具體實作步驟如下:
1、新建CSVUtils.java檔:
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.FileNotFoundException;import java.io.FileOutputStreamStreamStreamimport 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; .util.Map;import javax.servlet.http.HttpServletResponse;import org.apache.commons.beanutils.BeanUtils;/** * 檔案操作*/public class CSVUtils { /** * 產生為CVS檔案* @param exportData * 來源資料List * @param map * csv檔案的清單頭map * @param outPutPath * 檔案路徑* @param fileName * 檔案名稱* @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(outFile); .mkdir(); } //定義檔案名稱格式並建立csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath)); System.out.println("csvFile:" + csvFile); // UTF-8使正確讀取取分隔符號"," csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream( csvFile), "UTF-8"), 1024); System.out.println("csvFileOutputStream:" + csvFileOutputStream); // 寫入檔案頭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(); // 寫入檔案內容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 (tils.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; } /** *下載檔案* @param response * @param csvFilePath * 檔案路徑* @param fileName * 檔案名稱* @throws IOException */ public static void exportFile(HttpServletResponse response, String csvFilePath, String fileName throw IOString fileName. response.setContentType("application/csv;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); InputStream in in include + URLEncoder.encode(fileName, "UTF-8")); InputStream in in include = 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); } } } } /** * 刪除該目錄filePath下的所有檔案* @param filePath *檔案目錄路徑*/ 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(); } } } } /** * 刪除單一檔案* @param filePath * 檔案目錄路徑* @param fileName * 檔案名稱*/ 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; } } } } } /* * * 測試資料* @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", "第一列"); map.put("2", "第二列"); map.put("3", "第三列"); map.put(" 4", "第四列"); String path = "c:/export/"; String fileName = "檔案匯出"; File file = CSVUtils.createCSVFile(exportData, map, path, fileName); String fileName2 = file.getName(); System.out.println("檔案名稱:" + fileName2); }}
2、呼叫createCSVFile方法產生CSV文件
String name = "銀行退款資料";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", "訂單號碼"); map.put("2", "付款日期"); map.put("3", "退貨現金金額(整數金額單位:分)"); map.put("4", "退貨原因"); File file = CSVUtils.createCSVFile(exportData , map, filePath, name);//產生CSV檔案fileName = file.getName(); CSVUtils.exportFile(response, filePath + fileName, fileName);//下載產生的CSV文件