欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java生成CSV文件實(shí)例詳解

 更新時間:2014年07月25日 10:40:49   投稿:shichen2014  
這篇文章主要介紹了Java生成CSV文件的方法,很實(shí)用的功能,需要的朋友可以參考下

本文實(shí)例主要講述了Java生成CSV文件的方法,具體實(shí)現(xiàn)步驟如下:

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.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 {

  /**
   * 生成為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), "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();
      // 寫入文件內(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()));
          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)
                                                  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);
        }
      }
    }
  }

  /**
   * 刪除該目錄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;
          }
        }
      }
    }
  }

  /**
   * 測試數(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文件

String name = "銀行退款數(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", "訂單號");
 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文件

相關(guān)文章

  • Java中字符串常見題之String相關(guān)講解

    Java中字符串常見題之String相關(guān)講解

    今天小編就為大家分享一篇關(guān)于Java中字符串常見題之String相關(guān)講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Java基于Socket實(shí)現(xiàn)HTTP下載客戶端

    Java基于Socket實(shí)現(xiàn)HTTP下載客戶端

    這篇文章主要介紹了Java基于Socket實(shí)現(xiàn)HTTP下載客戶端的相關(guān)資料,感興趣的小伙伴們可以參考一下
    2016-01-01
  • springboot解決Class path contains multiple SLF4J bindings問題

    springboot解決Class path contains multiple 

    這篇文章主要介紹了springboot解決Class path contains multiple SLF4J bindings問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Spring中WebClient的創(chuàng)建和使用詳解

    Spring中WebClient的創(chuàng)建和使用詳解

    這篇文章主要介紹了Spring中WebClient的創(chuàng)建和使用詳解,在Spring5中,出現(xiàn)了Reactive響應(yīng)式編程思想,并且為網(wǎng)絡(luò)編程提供相關(guān)響應(yīng)式編程的支持,如提供了WebFlux,它是Spring提供的異步非阻塞的響應(yīng)式的網(wǎng)絡(luò)框架,需要的朋友可以參考下
    2023-11-11
  • JAVA 多態(tài) 由淺及深介紹

    JAVA 多態(tài) 由淺及深介紹

    JAVA 多態(tài) 由淺及深介紹,什么是多態(tài)?多態(tài)的詳細(xì)解釋,多態(tài)的好處,多態(tài)的實(shí)際運(yùn)用等
    2013-03-03
  • chatgpt java環(huán)境調(diào)用源碼實(shí)現(xiàn)demo

    chatgpt java環(huán)境調(diào)用源碼實(shí)現(xiàn)demo

    這篇文章主要介紹了chatgpt java環(huán)境調(diào)用源碼實(shí)現(xiàn)demo,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-02-02
  • mybatisplus解決駝峰命名映射問題詳解

    mybatisplus解決駝峰命名映射問題詳解

    這篇文章主要介紹了mybatisplus解決駝峰命名映射問題詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • Mybatis中單雙引號引發(fā)的慘案及解決

    Mybatis中單雙引號引發(fā)的慘案及解決

    這篇文章主要介紹了Mybatis中單雙引號引發(fā)的慘案及解決方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • java微信公眾號開發(fā)(搭建本地測試環(huán)境)

    java微信公眾號開發(fā)(搭建本地測試環(huán)境)

    這篇文章主要介紹了java微信公眾號開發(fā),主要內(nèi)容有測試公眾號與本地測試環(huán)境搭建,需要的朋友可以參考下
    2015-12-12
  • Ajax實(shí)現(xiàn)省市區(qū)三級聯(lián)動

    Ajax實(shí)現(xiàn)省市區(qū)三級聯(lián)動

    這篇文章主要為大家詳細(xì)介紹了jQuery ajax實(shí)現(xiàn)省市縣三級聯(lián)動的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能幫助到你
    2021-07-07

最新評論