1.引入javacsv.jar
2.导出.cvs文件
public static void exportCvs(String rootPath, String[] header, List<Map> list, OutputStream out){
try {
System.out.println(rootPath);
CsvWriter csvWriter = new CsvWriter(rootPath,',', Charset.forName("UTF-8"));
//写入表头信息
csvWriter.writeRecord(header);
for(int i=0,size=list.size();i<size;i++){
Map map = list.get(i);
String bianhao=map.get("bianhao").toString();
String xingming=map.get("xingming").toString();
String zjhm=map.get("zjhm").toString();
String zjlx=map.get("zjlx").toString();
String phone=map.get("phone").toString();
csvWriter.write(bianhao);
csvWriter.write(xingming);
csvWriter.write(zjhm);
csvWriter.write(zjlx);
csvWriter.write(phone);
csvWriter.endRecord();
}
File file = new File(rootPath);
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int n;
while((n=fis.read(b))!=-1){
out.write(b,0,n);
}
fis.close();
csvWriter.close();
}catch (Exception e){
e.printStackTrace();
}
}
3.测试
String [] headers={"编号","姓名","证件号码","证件类型","手机号码"};
String rootPath="C:\\Users\\lyj\\Desktop\\cs.cvs";
List list = queryForList("yct.ac01");
FileOutputStream out = new FileOutputStream(new File(rootPath));
try{
CsvUtils.exportCvs(rootPath,headers,list,out);
out.flush();
out.close();
}catch (Exception e){
e.printStackTrace();
}