1.生成CSV文件的工具类:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
public class CsvUtils {
/**
* List数据生成CSV文件(逗号分隔文件)
* @param head 头部数据
* @param dataList 表格数据
* @param outPutPath csv存放的路径
* @param filename 生成的文件名
* @return
*/
public static File createCsvFile(List<Object> head,List<List<Object>> dataList,
String outPutPath,String filename){
File csvFile = null;
BufferedWriter csvWriter = null;
try {
//1.生成CSV文件
csvFile = new File(outPutPath + File.separator + filename + ".csv");
//生成路径所需的父文件夹,如果需要的话
File parent = csvFile.getParentFile();
if(parent != null && !parent.exists()){
parent.mkdirs();
}
csvFile.createNewFile();
//2.GB2312正确读取","
csvWriter = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(csvFile),"GB2312"),1024);
//写入头部
writeRow(head, csvWriter);
//写入内容
for(List<Object> row : dataList){
writeRow(row, csvWriter);
}
csvWriter.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
csvWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return csvFile;
}
/**
* 往csv文件写一行数据的方法
* @param row
* @param csvWriter
* @throws IOException
*/
private static void writeRow(List<Object> row,BufferedWriter csvWriter) throws IOException{
for(Object data : row){
StringBuffer sb = new StringBuffer();
String rowStr = sb.append("\"").append(data).append("\",").toString();
csvWriter.write(rowStr);
}
csvWriter.newLine();
}
}
2.模拟数据,进行生成
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class testCsv {
@Test
public void moni(){
//模拟数据
//头部
List<Object> exportData = new ArrayList<Object>();
exportData.add("第一列");
exportData.add("第二列");
exportData.add("第三列");
//表格
List<List<Object>> datalist = new ArrayList<List<Object>>();
//第一行
List<Object> data=new ArrayList<Object>();
data.add("111");
data.add("222");
data.add("333");
//第二行
List<Object> data1=new ArrayList<Object>();
data1.add("444");
data1.add("555");
data1.add("666");
datalist.add(data);
datalist.add(data1);
String path = "G:/Poi/";
String fileName = "文件导出";
File file = CsvUtils.createCsvFile(exportData, datalist, path, fileName);
String fileName2 = file.getName();
System.out.println("文件名称:" + fileName2);
}
}