poi导出excel并设置密码

以下是关键部分代码

ByteArrayOutputStream bout = new ByteArrayOutputStream();
        wb.write(bout);
        bout.flush();
        ByteArrayInputStream Workbookinput = new ByteArrayInputStream(bout.toByteArray());
        POIFSFileSystem fs = null;
        FileOutputStream fos= null;
        try {
            fs = new POIFSFileSystem(Workbookinput);
            HSSFWorkbook wbbook = new HSSFWorkbook(fs);
            Biff8EncryptionKey.setCurrentUserPassword("ouma");
            wbbook.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(),"admin");
            // wb.unwriteProtectWorkbook();
            String nrString =ksmc+"模板导出";
            response.setHeader("Content-disposition", "attachment;filename="+new
                    String(nrString.getBytes("gb2312"), "ISO8859-1") + ".xls");
            OutputStream ouputStream = response.getOutputStream();
            wbbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 首先需要在项目的pom.xml文件中引入easypoi的依赖: ``` <dependency> <groupId>cn.afterturn</groupId> <artifactId>easypoi-base</artifactId> <version>4.1.0</version> </dependency> ``` 2. 创建一个实体类,用于表示需要导出的数据,例如: ``` public class User { @Excel(name = "ID") private Integer id; @Excel(name = "用户名") private String username; @Excel(name = "密码") private String password; // 省略getter和setter方法 } ``` 注意,这里使用了easypoi提供的@Excel注解,用于指定导出excel文件中的列名。 3. 在Controller中编写导出Excel文件的代码,例如: ``` @RequestMapping("/export") public void export(HttpServletResponse response) throws IOException { List<User> userList = userService.getAllUsers(); // 创建Excel导出对象 ExcelExportUtil.exportExcel(new ExportParams("用户列表", "用户"), User.class, userList, new FileOutputStream("user.xlsx"), ExcelType.XSSF); // 设置响应头 response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=user.xlsx"); // 将文件输出到响应流中 FileInputStream inputStream = new FileInputStream("user.xlsx"); ServletOutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } inputStream.close(); outputStream.flush(); outputStream.close(); } ``` 这里使用了ExcelExportUtil类提供的exportExcel方法来导出Excel文件,其中: - ExportParams对象用于指定导出Excel文件的标题和sheet名; - User.class参数用于指定导出的数据类型; - userList参数是需要导出的数据; - FileOutputStream对象用于将导出Excel文件保存到磁盘上; - ExcelType参数用于指定导出Excel文件类型。 最后,将导出Excel文件输出到响应流中,使浏览器能够下载该文件。 注意,这里需要将Excel文件保存到磁盘上,并从磁盘上读取文件并输出到响应流中,这可能会对性能产生一定的影响。如果需要提高性能,可以考虑使用POI提供的SXSSFWorkbook类,该类可以在内存中生成Excel文件,避免频繁的磁盘读写操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值