根据数据批量生成excel文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xm526489770/article/details/80741335

第一步导入依赖:

<!--excel支持-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.11</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.11</version>
</dependency>

第二步前端控制器实现:

/**
 * 文件导出功能
 */
@GetMapping("/test")
public String export(HttpServletResponse response){

    //查询所有区域信息
    List<String> list = new ArrayList<>();
    list.add("aaa");
    list.add("bbb");
    list.add("ccc");
    List<String> list2=new ArrayList<>();
    list2.add("ddd");
    list2.add("eee");
    list2.add("fff");
    //创建Excel 工作对象
   // HSSFWorkbook hssfWorkbook=new HSSFWorkbook();
    //使用最新的工作对象
    SXSSFWorkbook sxssfWorkbook=new SXSSFWorkbook();
    for (String s : list2) {
        //创建sheet
        //HSSFSheet sheet = hssfWorkbook.createSheet(s);

        Sheet sheet = sxssfWorkbook.createSheet(s);
        Row row = sheet.createRow(0);
        //创建行
       // HSSFRow row = sheet.createRow(0);
        //创建表空间字段
        row.createCell(0).setCellValue("区域编号");
        row.createCell(1).setCellValue("省份");
        row.createCell(2).setCellValue("");
        row.createCell(3).setCellValue("区县");

        //遍历集合创建表信息
        for (int i = 0; i < list.size(); i++) {

            //获得区域对象
            String area2 = list.get(i);

            //创建行
           // HSSFRow createRow = sheet.createRow(i+1);
            Row createRow = sheet.createRow(i + 1);

            //创建行内字段
            createRow.createCell(0).setCellValue(area2);

        }
    }


    //创建文件名
    String filename="fq3.xlsx";
    //创建输出对象
    OutputStream out ;
    response.setContentType("application/ms-excel;charset=UTF-8");
    try {
       
response.setHeader( "Content-Disposition", "attachment;filename=" +
        new String( filename.getBytes("gb2312"), "ISO8859-1" ) );
out = response.getOutputStream (); sxssfWorkbook.write (out ); // 将数据写出去 String str = " 导出 " + filename + " 成功! "; System. out.println (str ); out.close (); } catch (Exception e ) { e.printStackTrace (); e.printStackTrace (); String str1 = " 导出 " + filename + " 失败! "; System. out.println (str1 ); } return null; }

第三步测试页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试页面</title>
    <script src="./ckplayer/ckplayer.js"></script>
</head>
<body>
<!--<a href="/group/download?from=1528770630000&to=1529029830000">下载</a>-->
<a href="/dome/test"></a>
</body>
</html>

第四步实现效果:


猜你喜欢

转载自blog.csdn.net/xm526489770/article/details/80741335