csv文件读写工具类

示例代码:

package com.harvey.changyong.common;


import com.ibm.wsdl.util.StringUtils;

import java.io.*;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * csv文件工具类
 */
public final class CsvFileUtil {

    /**
     * 创建 csv 文件
     *
     * @param exportData 待写入的数据
     * @param headers    文件头部
     * @param outPutPath 文件路径
     * @param fileName   文件名
     * @return
     */
    public static File createCSVFile(List exportData, LinkedHashMap headers, String outPutPath, String fileName) {
        File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            File file = new File(outPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //定义文件名格式并创建
            csvFile = new File(outPutPath + fileName + ".csv");
            file.createNewFile();
            // UTF-8使正确读取分隔符","
            //如果生产文件乱码,windows下用gbk,linux用UTF-8
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                    csvFile), "UTF-8"), 1024);

            // 写入文件头部
            for (Iterator propertyIterator = headers.entrySet().iterator(); propertyIterator.hasNext(); ) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                csvFileOutputStream.write(propertyEntry.getValue() != null ? String.valueOf(propertyEntry.getValue()) : "");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }
            csvFileOutputStream.newLine();
            // 写入文件内容
            for (Iterator iterator = exportData.iterator(); iterator.hasNext(); ) {
                Object row = iterator.next();
                if (Objects.isNull(row)) {
                    continue;
                }
                for (Iterator propertyIterator = headers.entrySet().iterator(); propertyIterator
                        .hasNext(); ) {
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                    Object cellData = ((Map) row).get(propertyEntry.getKey());
                    String str = !Objects.isNull(cellData) ? String.valueOf(cellData) : "";
                    if (str == null) {
                        str = "";
                    } else {
                        //ps:由于csv文件主要采用逗号进行分割,因此保证数据中\加双引号都好加双引号,换行符去掉。
                        str = str.replaceAll("\r|\n", "").replaceAll("\"", "\"\"").replaceAll(",", "\"\"");

                        //字符串以0开头的数据在Excel中会自动去0,避免此问题用=""替换如0009->="0009"既可原样展示
                        if (str.startsWith("0")) {
                            str = "=" + '"' + str + '"';
                        }
                    }
                    csvFileOutputStream.write(str);
                    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;
    }

    /**
     * 解析 csv 文件
     *
     * @param headerStartRow 文件头部开始行 从 0 开始
     * @param dataStartRow   实际数据开始行 从 0 开始
     * @return java.util.LinkedHashMap
     * @Param inputStream 文件输入流
     **/
    public static List<LinkedHashMap> readCSVFile(InputStream inputStream, int headerStartRow, int dataStartRow) {
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        AtomicInteger currentStartRow = new AtomicInteger(-1);
        String line = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            String headerLine = "";
            List<String> dataLineList = new ArrayList<>();
            while ((line = bufferedReader.readLine()) != null) {
                if (line.trim().equals("")) {
                    continue;
                }
                int rowNumber = currentStartRow.incrementAndGet();
                if (rowNumber == headerStartRow) {
                    headerLine = line;
                }
                if (rowNumber >= dataStartRow) {
                    dataLineList.add(line);
                }
            }
            //字段名
            List<LinkedHashMap> linkedHashMapList = new ArrayList<>();
            String[] fieldNames = headerLine.split(",");
            for (String dataLine : dataLineList) {
                LinkedHashMap dataLinkedMap = new LinkedHashMap<>();
                String[] dataValues = dataLine.split(",");
                for (int i = 0; i < dataValues.length; i++) {
                    String fieldName = fieldNames[i];
                    if (fieldName == null || "".equals(fieldName)) {
                        continue;
                    }
                    String dataVal = dataValues[i];
                    if (dataVal == null) {
                        dataVal = "";
                    }
                    dataLinkedMap.put(fieldName, dataVal);
                }
                linkedHashMapList.add(dataLinkedMap);
            }
            return linkedHashMapList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 测试验证
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        writeFile();
        readFile();
    }

    private static void writeFile() {
        LinkedHashMap fileHeaders = new LinkedHashMap();
        fileHeaders.put("id", "编号");
        fileHeaders.put("name", "姓名");
        fileHeaders.put("age", "年龄");
        fileHeaders.put("school", "学校");
        fileHeaders.put("remark", "备注");

        List<Map<String, Object>> dataList = new ArrayList();
        Map m1 = new HashMap();
        m1.put("id", 1);
        m1.put("name", "张三");
        m1.put("age", 24);
        m1.put("school", "广工");
        m1.put("remark", "好学校");

        Map m2 = new HashMap();
        m2.put("id", 2);
        m2.put("name", "李四");
        m2.put("age", 26);
        m2.put("school", "海南");
        m2.put("remark", "00009");
        dataList.add(m1);
        dataList.add(m2);

        String createFilePath = "D:/javatest/createCSVFile/";
        File directory = new File(createFilePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File csvFile = CsvFileUtil.createCSVFile(dataList, fileHeaders, createFilePath, "tempFile");
    }

    private static void readFile() throws FileNotFoundException {
        String file = "D:/javatest/createCSVFile/tempFile.csv";
        FileInputStream inputStream = new FileInputStream(file);
        List<LinkedHashMap> hashMapList = readCSVFile(inputStream, 0, 1);
        System.out.println(hashMapList);
    }
}

 

posted @ 2022-06-10 13:16  残城碎梦  阅读(154)  评论(0编辑  收藏  举报