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、解析信息如下: