Java生成CSV文件簡單操做實例

Java生成CSV文件簡單操做實例java

 

CSV是逗號分隔文件(Comma Separated Values)的首字母英文縮寫,是一種用來存儲數據的純文本格式,一般用於電子表格或數據庫軟件。在 CSV文件中,數據「欄」以逗號分隔,可容許程序經過讀取文件爲數據從新建立正確的欄結構,並在每次遇到逗號時開始新的一欄。如:數據庫

1,張三,男
2,李四,男
3,小紅,女

Java生成CSV文件(建立與導出封裝類)apache

package com.yph.omp.common.util;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.junit.Test;

/**
 * Java生成CSV文件
 */
public class CSVUtil {

    /**
     * 生成爲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(outPutPath);
            if (!file.exists()) {
                file.mkdir();
            }
            // 定義文件名格式並建立
            csvFile = File.createTempFile(fileName, ".csv",
                    new File(outPutPath));
            // UTF-8使正確讀取分隔符","
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(csvFile), "GBK"), 1024);
            // 寫入文件頭部
            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();
            /*-------------------------------*/  //如下部分根據不一樣業務作出相應的更改 StringBuilder sbContext
= new StringBuilder(""); if (null != BeanUtils.getProperty(row,(String) propertyEntry.getKey())) { if("證件號碼".equals(propertyEntry.getValue())){ //避免:身份證號碼 ,讀取時變換爲科學記數 - 解決辦法:加 \t(用Excel打開時,證件號碼超過15位後會自動默認科學記數) sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t"); }else{ sbContext.append(BeanUtils.getProperty(row,(String) propertyEntry.getKey())); } } csvFileOutputStream.write(sbContext.toString());             /*-------------------------------*/ 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(HttpServletRequest request, HttpServletResponse response, String csvFilePath, String fileName) throws IOException { response.setCharacterEncoding("UTF-8"); response.setContentType("application/csv;charset=GBK"); response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1")); InputStream in = null; try { in = new FileInputStream(csvFilePath); int len = 0; byte[] buffer = new byte[1024]; OutputStream out = response.getOutputStream(); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (FileNotFoundException e1) { System.out.println(e1); } finally { if (in != null) { try { in.close(); } catch (Exception e1) { throw new RuntimeException(e1); } } } } /** * 刪除該目錄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; } } } } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void createFileTest() { 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 = "d:/export"; String fileName = "文件導出"; File file = CSVUtil.createCSVFile(exportData, map, path, fileName); String fileNameNew = file.getName(); String pathNew = file.getPath(); System.out.println("文件名稱:" + fileNameNew ); System.out.println("文件路徑:" + pathNew ); } }//注:BeanUtils.getProperty(row,(String) propertyEntry.getKey()) + "\t" ,只爲解決數字格式超過15位後,在Excel中打開展現科學記數問題。
相關文章
相關標籤/搜索