文章正文

Java-CSV工具类

【文章】2020-04-23

简介Java-CSV工具类

在pom文件中添加jar依赖

<dependency>
	<groupId>net.sourceforge.javacsv</groupId>
	<artifactId>javacsv</artifactId>
	<version>2.0</version>
</dependency>

工具类

package com.sto.pdd.util;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class CSVUtil {
    public static char separator = ',';

    public static void main(String[] args) throws Exception {
        // 测试导出
        String filePath = "D:/scoreInfo.csv";
        List<String[]> dataList = new ArrayList<String[]>();
        //添加标题
        dataList.add(new String[]{"学号", "姓名", "分数"});
        for (int i = 0; i < 10; i++) {
            dataList.add(new String[]{"2010000" + i, "张三" + i, "8" + i});
        }
        createCSV(dataList, filePath);

        // 读取CSV文件
        readCSV(filePath);
    }

    /**
     * 读取CSV文件
     * @param filePath:全路径名
     */
    public static List<String[]> readCSV(String filePath) throws Exception {
        CsvReader reader = null;
        List<String[]> dataList = new ArrayList<String[]>();
        try {
            //如果生产文件乱码,windows下用gbk,linux用UTF-8
            reader = new CsvReader(filePath, separator, Charset.forName("GBK"));

            // 读取表头
            reader.readHeaders();
            String[] headArray = reader.getHeaders();//获取标题
            System.out.println(headArray[0] + headArray[1] + headArray[2]);

            // 逐条读取记录,直至读完
            while (reader.readRecord()) {
                // 读一整行
                System.out.println(reader.getRawRecord());
                // 读这行的第一列
                System.out.println(reader.get("学号"));
                // 读这行的第二列
                System.out.println(reader.get(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != reader) {
                reader.close();
            }
        }

        return dataList;
    }

    /**
     * 生成CSV文件
     * @param dataList:数据集
     * @param filePath:全路径名
     */
    public static boolean createCSV(List<String[]> dataList, String filePath) throws Exception {
        boolean isSuccess = false;
        CsvWriter writer = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath, true);
            //如果生产文件乱码,windows下用gbk,linux用UTF-8
            writer = new CsvWriter(out, separator, Charset.forName("GBK"));
            for (String[] strs : dataList) {
                writer.writeRecord(strs);
            }
            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                writer.close();
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return isSuccess;
    }
}


写入注意问题:

Java后台将数据写入CSV文件时踩过的坑:写入一些数据(例如我碰到过的:订单日期、联行行号、(收款)银行账号、金额)时候,由于数字比较多会导致显示成缩略形式或者科学计数法。


解决方法:

在写入字段时候,在可能发生缩略的地方加上" "【" "为“转义字符”,代表的是一个tab,也就是8个空格】


文件乱码:

当遇到utf-8导出到csv文件时出现乱码,需要一个BOM头。

private static void writeBcp() throws IOException {
    //Create bcp file if not exist  
    File bcpFile = new File("test.csv");
    //bcpFile.delete();  
    byte[] bom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
    //boolean newFile = false;  
    FileOutputStream bcpFileWriter = new FileOutputStream(bcpFile);
    bcpFileWriter.write(bom);
    //bcpFile.delete();  
    String title = ""MD5","扫描文件名","扫描时间"," +
            ""是否病毒","安全等级","病毒英文名称"," +
            ""病毒变种","病毒类型","病毒影响"," +
            ""感染系统","传播方式","备注"";

    bcpFileWriter.write((new String(title.getBytes(), "utf-8")).getBytes());
    bcpFileWriter.write("
".getBytes());

    String appStr = """ + 123 + "","
            + """ + 123 + "","
            + 123 + ","
            + 123 + ","
            + 123 + ","
            + """ + 123 + "","
            + ""","
            + 123 + ","
            + """ + 123 + "","
            + """ + 123 + "","
            + """ + 123 + "","
            + """ + 123 + ""
";

    bcpFileWriter.write(appStr.getBytes());
    bcpFileWriter.close();
}

打赏支持

感谢您的支持,加油!

打开微信扫码打赏,你说多少就多少

找书费时,联系客服快速获取!

扫码支持

在线客服8:30-22:30,若离线请留言!

获取教程,请联系在线客服!

扫码支持

在线客服8:30-22:30,若离线请留言!

热门阅读

找PDF电子书,太费时间?

  • 微信扫描二维码,让客服快速查找。
  • 在线客服8:30-22:00,若离线请留言!