首先我們需要對csv文件有基礎的認識,csv文件類似excel,可以使用excel打開,但是csv文件的本質是逗號分隔的,對比如下圖:
txt中顯示:
修改文件后綴為csv后顯示如下:
在java中我們一般使用poi操作excel,導入,導出都可以,但是poi很消耗內存,尤其在導出時,這個時候我們其實可以選擇導出生成csv文件,因為其跟文本差不多,所以效率很高。
簡單寫了一個實現類,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
/** * * 導出生成csv格式的文件 * @author ccg * @param titles csv格式頭文 * @param propertys 需要導出的數據實體的屬性,注意與title一一對應 * @param list 需要導出的對象集合 * @return * @throws IOException * Created 2017年1月5日 上午10:51:44 * @throws IllegalAccessException * @throws IllegalArgumentException */ public static <T> String exportCsv(String[] titles,String[] propertys,List<T> list) throws IOException, IllegalArgumentException, IllegalAccessException{ File file = new File( "d:\\test.csv" ); //構建輸出流,同時指定編碼 OutputStreamWriter ow = new OutputStreamWriter( new FileOutputStream(file), "gbk" ); //csv文件是逗號分隔,除第一個外,每次寫入一個單元格數據后需要輸入逗號 for (String title : titles){ ow.write(title); ow.write( "," ); } //寫完文件頭后換行 ow.write( "\r\n" ); //寫內容 for (Object obj : list){ //利用反射獲取所有字段 Field[] fields = obj.getClass().getDeclaredFields(); for (String property : propertys){ for (Field field : fields){ //設置字段可見性 field.setAccessible( true ); if (property.equals(field.getName())){ ow.write(field.get(obj).toString()); ow.write( "," ); continue ; } } } //寫完一行換行 ow.write( "\r\n" ); } ow.flush(); ow.close(); return "0" ; } |
測試類如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public void test() throws IOException, IllegalArgumentException, IllegalAccessException{ String[] titles = new String[]{ "ID" , "姓名" }; String[] propertys = new String[]{ "id" , "name" }; List<User> list = new ArrayList<User>(); User user; user = new User(); user.setId(1L); user.setName( "張三" ); list.add(user); user = new User(); user.setId(2L); user.setName( "李四" ); list.add(user); CsvUtil.getInstance().exportCsv(titles,propertys, list); } |
導出后生成的文件跟上圖一樣,算是一個封裝吧,傳入表頭,以及表頭對應實體的屬性即可,注意要一一對應。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。