poi根据模板导出excel

这篇博客介绍了如何利用Apache POI库根据模板来创建Excel文件。首先,通过Maven引入Apache POI依赖,然后从指定路径加载模板文件。接着,遍历数据列表填充到Excel模板的指定单元格中。最后,提供了两种导出Excel的方式,一种是保存到本地,另一种是通过HTTP响应直接下载。前端可以通过重定向请求触发下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.引入poi包

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
</dependency>

2.获取模板

String filePath = request.getSession().getServletContext().getRealPath("") + "xxx.xls";

HSSFWorkbook workbook = null;
try {
      //获取模板
      File file = new File(filePath);
      FileInputStream input = new FileInputStream(file);
      workbook = new HSSFWorkbook(input);
} catch (IOException e) {
      e.printStackTrace();
}

HSSFSheet sheet = workbook.getSheetAt(0);

HSSFRow row = null;
HSSFCell cell = null;

3.填充数据

List datas = service.getDatas();

int cellIndex = 0;

//获取最后一行

int curRowIndex = sheet.getLastRowNum();

row = sheet.createRow(curRowIndex+1):

cell = row.getCell(cellIndex++):

cell.setCellValue("第一格数据");

cell = row.getCell(cellIndex++):

cell.setCellValue("第二格数据");

cell = row.getCell(cellIndex++):

cell.setCellValue("第三格数据");

4.导出

导出有两种方式,第一是指定导出位置,第二是弹出下载

指定导出位置的导出方式:

try{

    FileOutputStream output = new FileOutputStream(new File("D:\\测试.xls"));

    workbook.write(ouput);

    output.close();

}catch(IOException e){

    e.printStackTrace();

}

弹出下载方式:

try {
      String fileName = "测试.xls";
      response.reset();
      response.setContentType("application/msexcel");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Content-Disposition","attchment;filename="+new String((fileName.getBytes()),"iso-8859-1"));
      OutputStream out = response.getOutputStream();
      workbook.write(out);
      out.flush();
      out.close();
 } catch (IOException e) {
      e.printStackTrace();
 }

5.前端请求

window.location.href = "xxxAction.do?action=xxx";

弹出下载不支持ajax请求,因为ajax请求的response是二进制流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值