csv文件为逗号分隔符文件,以下代码为读取数据库数据,输出为csv格式文件。
public static void exportloggers(String filepath,List<bean类对象> list) {
String []titles = new String[]{"seq","certid","userid","datetime"};//标题
//获取当前时间并转化格式 用时间为文件命名
long time = new Date().getTime();
Date date=new Date(time);
SimpleDateFormat sdf_=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1=new SimpleDateFormat("HH-mm-ss");
String fileName = "logger_"+ sdf.format(date) + "_" + sdf1.format(date);
File csvFile = null;
BufferedWriter csvFileOutputStream = null;
try {
File file = new File(filepath);
if (!file.exists()) {
file.mkdir();
}
// 定义文件名格式并创建
csvFile = File.createTempFile(fileName, ".csv", new File(filepath));
System.out.println("csvFile:" + csvFile);
// UTF-8使正确读取分隔符","
csvFileOutputStream = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(csvFile), "utf-8"),1024);
System.out.println("csvFileOutputStream:" + csvFileOutputStream);
// 写入文件头部
for (int i=0;i<titles.length;i++) {
csvFileOutputStream.write(titles[i]);
//不是最后一个字段,加入逗号分隔符
if (i!=titles.length-1) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.newLine();
//写内容
for(Object obj : list){
//利用反射获取所有字段
Field[] fields = obj.getClass().getDeclaredFields();
int i =0;
for(String property : titles){
for(Field field : fields){
//设置字段可见性
field.setAccessible(true);
if(property.equals(field.getName())){
if(field.get(obj)!=null&&!"".equals(field.get(obj))) {
//判断字段为时间格式时 对字段进行转换
if(field.getName().equals("datetime"))
csvFileOutputStream.write(sdf_.format((Date)field.get(obj)));
else
//字段前后增加“"”是为了避免字段中出现逗号,与字段的逗号分隔符混淆
csvFileOutputStream.write("\""+field.get(obj).toString().replace("\"", "'")+"\"");
}else
csvFileOutputStream.write("");
//不是最后一个字段 加入逗号分隔符
if(i!=titles.length-1)
csvFileOutputStream.write(",");
}
}
i++;
}
//写完一行换行
csvFileOutputStream.newLine();
}
csvFileOutputStream.flush();
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意:因为csv文件已逗号分隔例如:字段1,字段2 ,字段3
1、如果出现字段内容中包含“,”,此时只需要将字段用双引号扩起即可。如:“字段,1”,字段2,字段3
2、双引号扩起字段后,如果字段中本身包含双引号,此时已然会造成数据解析是出错,所以增加双引号同时利用
字符串的replace方法,将双引号替换为单引号。如:
String name = names.replace("\"","'");
3、解析信息如下: