POI报表导出


//第一步导入依赖jar包
     

   <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.17</version>
        </dependency>
        <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.17</version>
        </dependency>
        <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml-schemas</artifactId>
                <version>3.17</version>
        </dependency>

=================================================================
//可以给页面上设置一个按钮,给按钮一个点击事件来触发此方法
function exportExcel() {
            //条件有条件可以在此设置一个条件
            var accounttime = $.trim($("#accounttime").val());
            
            //跳转到后台的方法            
            window.location.href="http://localhost:8080/partyMetting/exportExcel?accounttime="+ accounttime;
    }


=================================================================

//后台代码
@RestController
@RequestMapping("/partyMetting")
public class test {

    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, HttpServletRequest request) throws Exception{

      //接收参数
      String accounttime = request.getParameter("accounttime");
      //查询数据,实际可通过传过来的参数当条件去数据库查询,在此我就用空集合(数据)来替代
      List<> list = new ArrayList<>();

      //创建poi导出数据对象
      SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook();

      //创建sheet页
      SXSSFSheet sheet = sxssfWorkbook.createSheet("sheet页名字");
      //创建表头
      SXSSFRow headRow = sheet.createRow(0);
      //设置表头信息
      headRow.createCell(0).setCellValue("序号");
      headRow.createCell(1).setCellValue("姓名");
      headRow.createCell(2).setCellValue("年龄");
      // 遍历上面数据库查到的数据
      for (PartyAllMettingFrequencyMonthlyEntity pm : list) {
        //序号
        int x = 1;
        //填充数据
        SXSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
        //序号
        dataRow.createCell(0).setCellValue(x);
        //看你实体类在进行填充
        dataRow.createCell(1).setCellValue(pm.username);
        dataRow.createCell(2).setCellValue(pm.age);
        x++;
      }

      // 下载导出
      String filename = "导出excel表格名字";
      // 设置头信息
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/vnd.ms-excel");
      //一定要设置成xlsx格式
      response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
      //创建一个输出流
      ServletOutputStream outputStream = response.getOutputStream();
      //写入数据
      sxssfWorkbook.write(outputStream);

      // 关闭
      outputStream.close();
      sxssfWorkbook.close();
    }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值