- maven地址,直接放到pom.xml中
<!--csv处理--> <dependency> <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> <version>2.0</version> </dependency>
工具类代码,如下:
package com.telelands.util;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* csv工具类
*/
public class CsvUtils {
public static char separator = ',';
public static void main(String[] args) {
// 测试导出
// String filePath = "F:\\data\\gd_xzl.csv";
String filePath = "F:\\company_info.csv";
// 读取CSV文件
readCSV(filePath);
}
/**
* 读取CSV文件
* @param filePath:全路径名
*/
public static List<String[]> readCSV(String filePath) {
CsvReader reader = null;
List<String[]> dataList = new ArrayList<>();
try {
//如果生产文件乱码,windows下用gbk,linux用UTF-8
reader = new CsvReader(filePath, separator, Charset.forName("UTF-8"));
// 读取表头
// reader.readHeaders();
// 逐条读取记录,直至读完
while (reader.readRecord()) {
dataList.add(reader.getValues());
}
} 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("UTF-8"));
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;
}
}

