java使用poi和反射生成excel

用到的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;
}

最终效果图如下:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值