Java后台导出csv文件到指定文件夹目录
main方法测试:
import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) throws IOException { List<User> list = new ArrayList<>(); User user1 = new User(); user1.setName("张三"); user1.setAge(20); user1.setSex("男"); list.add(user1); User user2 = new User(); user2.setName("李四"); user2.setAge(25); user2.setSex("女"); list.add(user2); String filePath = "E:\home\" + "test.csv"; String[] titles = new String[]{"姓名", "年龄", "性别"}; String[] proper = new String[]{"name", "age", "sex"}; try { ExportCsvUtil.exportCsv(titles, proper, list, filePath); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
ExportCsvUtil工具类
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.Field; import java.util.List; public class ExportCsvUtil { /** * 导出生成csv格式的文件 * * @param titles csv格式头文 * @param propertys 需要导出的数据实体的属性,注意与title一一对应 * @param list 需要导出的对象集合 * @return * @throws IllegalAccessException * @throws IllegalArgumentException * @author ccg */ public static <T> String exportCsv(String[] titles, String[] propertys, List<T> list, String filePath) throws IOException, IllegalArgumentException, IllegalAccessException { File file = new File(filePath); //构建输出流,同时指定编码 OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(file), "gbk"); //csv文件是逗号分隔,除第一个外,每次写入一个单元格数据后需要输入逗号 for (String title : titles) { ow.write(title); ow.write(","); } //写完文件头后换行 ow.write(" "); //写内容 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(" "); } ow.flush(); ow.close(); return "0"; } }
测试结果:
打开预览:
下一篇:
编写程序实现顺序检索