JAVA中使用POI实现Excel 下载功能

1:需要准备的依赖项
 

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
<!--poi对excel2007以上版本的支持-->
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>

2:具体实现
 

public void download(HttpServletRequest request , HttpServletResponse response) throws IOException {
         String fileName = "template/init_meter1.xls"; //这个是xls模板,这个是Springboot项目中对应的resources的地址
         Resource classPathResource = new ClassPathResource(fileName); //这个Resource是用于读取
         OutputStream out = null;
         Workbook wb =  new HSSFWorkbook(classPathResource.getInputStream());//HSSFWorkbook是用于xls的操作
         Sheet sheet = wb.getSheet(wb.getSheetName(0));  //获取表格中sheet 的名字
         int row = 1;
        Row row1 = null;
        row1 = sheet.getRow(row);
        if (row1 == null) {
            row1 = sheet.createRow(row);
        }
        Cell cell1 = row1.getCell(0);   //获取到对应的单元格列
        if (cell1 == null) {
            cell1 = row1.createCell(0);
        }
         cell1.setCellValue("2"==null ? "" :"ABCDEFG"); //这里的数据可以动态生成,我这里是写死为了测试
         wb.setForceFormulaRecalculation(true);  //更新excel
         out=  response.getOutputStream();  //获得输出流
         response.setCharacterEncoding("UTF-8");
         response.setContentType("application/octet-stream; charset=UTF-8");
         response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        wb.write(out);
        if (out != null)
            out.close();  //关闭资源
    }
}

如果能帮到你们点个关注,定期更新一些有用的功能 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值