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.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; 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;/*** 文件操作* @author lizhiyong* @version $Id: CSVUtils.java, v 0.12014年7月22日 下午2:19:59 Exp $*/ public class CSVUtils {/*** 生成為CVS文件 * @param exportData* 源數(shù)據(jù)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(outPutPath);if (!file.exists()) {file.mkdir();}//定義文件名稱格式并創(chuàng)建csvFile = File.createTempFile(fileName, ".csv", new File(outPutPath));System.out.println("csvFile:" + csvFile);// UTF-8使正確讀取分隔符"," csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GBK"), 1024);System.out.println("csvFileOutputStream:" + csvFileOutputStream);// 寫(xiě)入文件頭部 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 ?new String( ((String) propertyEntry.getValue()).getBytes("GBK"), "GBK") : ""); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } System.out.println(new String(((String) propertyEntry.getValue()).getBytes("GBK"), "GBK")); } csvFileOutputStream.write("\r\n"); // 寫(xiě)入文件內(nèi)容 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()) != null? (String) propertyEntry.getKey() : "")); if (propertyIterator.hasNext()) { csvFileOutputStream.write(","); } } if (iterator.hasNext()) { csvFileOutputStream.write("\r\n"); } } 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) throws IOException { response.setContentType("application/csv;charset=GBK"); response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1")); //URLEncoder.encode(fileName, "GBK") InputStream in = null; try { in = new FileInputStream(csvFilePath); int len = 0; byte[] buffer = new byte[1024]; response.setCharacterEncoding("GBK"); 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(); } } } } /** * 刪除單個(gè)文件 * @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; } } } } } /** * 測(cè)試數(shù)據(jù) * @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 = "文件導(dǎo)出"; File file = CSVUtils.createCSVFile(exportData, map, path, fileName); String fileName2 = file.getName(); System.out.println("文件名稱稱:" + fileName2); } }
2、調(diào)用createCSVFile方法生成CSV文件
<span style="font-family:Courier New;">String name = "工商銀行(ICBC)退款數(shù)據(jù)"; 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", "訂單號(hào)"); map.put("2", "支付日期"); map.put("3", "退貨現(xiàn)金金額(整數(shù)金額 單位:分)"); map.put("4", "退貨原因"); File file = CSVUtils.createCSVFile(exportData, map, filePath, name);//生成CSV文件 fileName = file.getName(); CSVUtils.exportFile(response, filePath + fileName, fileName);//下載生成的CSV文件 </span>
版權(quán)聲明:本文博客原創(chuàng)文章。博客,未經(jīng)同意,不得轉(zhuǎn)載。
轉(zhuǎn)載于:https://www.cnblogs.com/zfyouxi/p/4751015.html
總結(jié)
以上是生活随笔為你收集整理的Java生成CSV文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 蟑螂能飞吗?
- 下一篇: 【C#】分享一个弹出容器层,像右键菜单那