<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.5</version>
</dependency>
import com.opencsv.CSVWriter;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class OpenCsvUtils {
public static void main(String[] args){
List<Object> head=new ArrayList<>();
head.add("编号");
head.add("姓名");
head.add("手机号");
List<List<Object>> dataList=new ArrayList<>();
List<Object> row1=new ArrayList<>();
row1.add("编号\n编号\n编号");
row1.add("姓名\n姓名\n姓名");
row1.add("手机号");
dataList.add(row1);
dataList.add(row1);
createCSVFile(head, dataList,"输出目录","文件名");
}
/**
* 写一行
* @param row
* @param csvWriter
*/
private static void writeRow(List<Object> row,CSVWriter csvWriter){
String[] rowStr=new String[row.size()];
for (int x=0;x<row.size();x++) {
rowStr[x]=row.get(x).toString();
}
csvWriter.writeNext(rowStr);
}
/**
* CSV文件生成方法
*
* @param head 标题行
* @param dataList 具体内容
* @param outPutPath 输出文件路径
* @param filename 文件名称
* @return 返回值
*/
public static File createCSVFile(List<Object> head, List<List<Object>> dataList,
String outPutPath, String filename) {
File csvFile = null;
FileOutputStream out= null;
CSVWriter csvWriter =null;
try {
csvFile = new File(outPutPath + File.separator + filename + ".csv");
File parent = csvFile.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
csvFile.createNewFile();
out = new FileOutputStream(csvFile);
csvWriter = new CSVWriter(new OutputStreamWriter(out,"utf-8"));
// 写入文件头部
writeRow(head, csvWriter);
//写入body
for(List<Object> row:dataList){
writeRow(row, csvWriter);
}
csvWriter.flush();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
csvWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
}
}