用到的pom如下:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
下面的属性字段自己看着写不用写太多
直接上核心代码:
public static void main(String[] args) throws IOException { //生成xls字段表头 String[] header = {"编码", "cities", "pop", "GDP", "GDP_Average", "GDP_Avrg(Dollar)", "lon", "lat", "level"}; Workbook wb=new HSSFWorkbook(); //创建工作簿 Sheet sheet = wb.createSheet(); //创建工作表 Row row=sheet.createRow(0); //在第一行创建字段名 for (int i=0;i<header.length;i++){ row.createCell(i).setCellValue(header[i]); } List<Result> list=result(); Object object=null; for (int j=0;j<list.size();j++){ Row row2=sheet.createRow(j+1); Result result=list.get(j); Field[] s=Result.class.getDeclaredFields();//利用反射获取所有的属性 for (int k=0;k<s.length;k++){ //循环所有的属性 String attributeName=s[k].getName(); //将所有的属性首字母大写 String methodName=attributeName.substring(0,1).toUpperCase()+attributeName.substring(1); try { Method getMethod=Result.class.getMethod("get"+methodName);//组合 getName() object=getMethod.invoke(result); //获取每个对象里面的属性值 System.out.println(object); if (object!=null){ //循环输出内容 row2.createCell(k).setCellValue(object.toString()); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } } //D:\FileSystemPath\HJZH\data\aaa.xls 我自己的路径 自己想放哪里都行 OutputStream outputStream=new FileOutputStream("D:\\FileSystemPath\\HJZH\\data\\aaa.xls"); wb.write(outputStream); } //模拟的数据 public static List<Result> result(){ List<Result> maps=new ArrayList<>(); //创建一个list集合 //链式赋值 实体类上的注解 @Builder Result result1=Result.builder().index(1).cities("北京").pop("2884.62").GDP("7894.24").GDP_Average("27367"). GDP_Avrg("4043").lon("106.504959").lat("29.533155").build(); Result result2=Result.builder().index(2).cities("上海").pop("2885.62").GDP("7895.24").GDP_Average("27368"). GDP_Avrg("4044").lon("107.504959").lat("30.533155").build(); maps.add(result1); maps.add(result2); return maps; }
最终效果图如下: