Export and generate csv files in java, and export csv files in java
First, we need to have a basic understanding of csv files. csv files are similar to excel and can be opened in excel. However, csv files are essentially separated by commas (,). For example:
Txt:
After the file suffix is changed to csv, the following information is displayed:
In java, we generally use poi to Operate excel, import, and export, but poi consumes a lot of memory. Especially when exporting, we can choose to export and generate csv files, because it is similar to text, it is very efficient.
A simple implementation class is written. The Code is as follows:
1/** 2*3 * export the attributes of the data entity to be exported to generate a csv file 4 * @ author ccg 5 * @ param titles csv format header 6 * @ param propertys, note that the title corresponds to a set of 7 * @ param list objects to be exported 8 * @ return 9 * @ throws IOException10 * Created January 5, 2017 * @ throws IllegalAccessException 12 * @ throws IllegalArgumentException 13*/14 public static <T> String exportCsv (String [] titles, string [] propertys, List <T> list) throws IOException, IllegalArgumentException, IllegalAccessException {15 File file = new File ("d: \ test.csv "); 16 // construct the output stream and specify the encoding 17 OutputStreamWriter ow = new OutputStreamWriter (new FileOutputStream (file), "gbk"); 18 19 // csv files are separated by commas, except for the first one, each time you write a cell data, you must enter a comma of 20 for (String title: titles) {21 ow. write (title); 22 ow. write (","); 23} 24 // wrap the line after the file header is written 25 ow. write ("\ r \ n"); 26 // write content 27 for (Object obj: list) {28 // obtain all fields Using Reflection 29 Field [] fields = obj. getClass (). getDeclaredFields (); 30 for (String property: propertys) {31 for (Field field: fields) {32 // set Field visibility 33 field. setAccessible (true); 34 if (property. equals (field. getName () {35 ow. write (field. get (obj ). toString (); 36 ow. write (","); 37 continue; 38} 39} 40} 41 // write a line wrap 42 ow. write ("\ r \ n"); 43} 44 ow. flush (); 45 ow. close (); 46 return "0"; 47}
The test class is as follows:
1 public void test () throws IOException, IllegalArgumentException, IllegalAccessException {2 String [] titles = new String [] {"ID", "name "}; 3 String [] propertys = new String [] {"id", "name"}; 4 List <User> list = new ArrayList <User> (); 5 User user; 6 user = new User (); 7 user. setId (1L); 8 user. setName ("Zhang San"); 9 list. add (user); 10 user = new User (); 11 user. setId (2L); 12 user. setName ("Li Si"); 13 list. add (user); 14 CsvUtil. getInstance (). exportCsv (titles, propertys, list); 15}
The file generated after export is the same. It is an encapsulation. You can import the table header and the attributes of the object corresponding to the table header.