First of all, we need to have a basic understanding of the csv file. The csv file is similar to excel and can be opened with excel, but the essence of the csv file is comma-separated, for example, the following figure:
Shown in txt:
After modifying the file suffix to csv, it will be displayed as follows:
In Java, we generally use poi to operate excel, import and export, but poi consumes memory very much, especially when exporting. At this time, we can actually choose to export to generate csv files, because it is similar to text, so it is very efficient.
I simply wrote an implementation class, the code is as follows:
/** * * Export the file that generates csv format* @author ccg * @param titles csv format header* @param properties The properties of the data entity that needs to be exported, pay attention to the corresponding one-to-one to the title* @param list The collection of objects that need to be exported* @return * @throws IOException * Created January 5, 2017 at 10:51:44 am * @throws IllegalAccessException * @throws IllegalArgumentException */ public static <T> String exportCsv(String[] titles,String[] properties,List<T> list) throws IOException, IllegalArgumentException, IllegalAccessException{ File file = new File("d://test.csv"); //Construct the output stream and specify the encoding OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(file), "gbk"); //The csv file is comma-separated. Except for the first one, you need to enter a comma after writing one cell data every time after writing one cell data, { ow.write(title); ow.write(","); } //Write line break after writing the file header ow.write("/r/n"); //Write content for(Object obj : list){ //Use reflection to get all fields Field[] fields = obj.getClass().getDeclaredFields(); for(String property : properties){ for(Field field : fields){ //Set field visibility field.setAccessible(true); if(property.equals(field.getName())){ ow.write(field.get(obj).toString()); ow.write(","); continue; } } } //After writing a line break ow.write("/r/n"); } ow.flush(); ow.close(); return "0"; }The test class is as follows:
public void test() throws IOException, IllegalArgumentException, IllegalAccessException{ String[] titles = new String[]{"ID","name"}; String[] properties = new String[]{"id","name"}; List<User> list = new ArrayList<User>(); User user; user = new User(); user.setId(1L); user.setName("Zhang San"); list.add(user); user = new User(); user.setId(2L); user.setName("Li Si"); list.add(user); CsvUtil.getInstance().exportCsv(titles,propertys, list); }The file generated after export is the same as the picture above, and is considered an encapsulation. Just pass in the header and the properties of the corresponding entity of the header. Pay attention to correspond one by one.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.