poi实现excel导出

 ServletRequestAttributes servletRequestAttributes = 
 (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String fileName = request.getParameter("fileName");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream outputStream = null;
        List<Client> clients = new ArrayList<Client>();
        clients.add(new Client("1", "100", "01"));
        clients.add(new Client("2", "200", "02"));

        List<String> biaoti = new ArrayList<String>(Arrays.asList("客户", "金额", "币种"));
        List<Integer> width = new ArrayList<>(
                Arrays.asList(4000, 6000, 8000)
        );

        // 创建工作簿
        HSSFWorkbook wb = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = wb.createSheet("客户");
        // 创建一行,行的索引从0开始,第一行为标题
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = null;
        // 设置第一行标题
        for (int i = 0; i < biaoti.size(); i++) {
            // 创建单元格,列的索引从0开始
            cell = row.createCell(i);
            cell.setCellValue(biaoti.get(i));
            sheet.setColumnWidth(i,width.get(i));
        }
        int rowcount = 1; //注意,excel第一行为标题,因此rowcount从1开始第二行填充数据
        try {
            for (int i = 0; i < clients.size(); i++) {
                // 等于row = sheet.createRow(rowcount) ; rowcount++
                row = sheet.createRow(rowcount++); 
                // 如果展示字段过多,考虑使用反射
                Client client = clients.get(i); //Client对应excel展示字段,顺序保持一致
                Field[] fields = client.getClass().getDeclaredFields(); //获取对应的所有展示字段
                Map<String, String> map = new HashMap<>();
                for (int j = 0; j < fields.length; j++) { //fields中属性顺序和Client属性顺序一致
                    Field field = fields[j];
                    field.setAccessible(true);
                    String name = field.getName(); // 属性名称
                    String value = String.valueOf(field.get(client)); //当前对象该属性的值
                    row.createCell(j).setCellValue(value); //设置
                }
            }
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值