java export data to Excel table (dynamically merge cells)

java exports data to Excel and dynamically merges cells based on data


need

Java exports data to an Excel table. The main information and associated information are one-to-many to generate table content similar to the figure below.

data table


accomplish

1.Introduce dependencies

code show as below:

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

2. Implement the code

code show as below:

    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response,OutChannelInfo outChannelInfo,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "20") Integer rows,
                            String sord,String sidx)throws Exception{
    
    
        //接收参数
        PageBean<OutChannelInfo> pageBean=outChannelService.findByPageCpid(outChannelInfo,"800033",page,rows,sord,sidx);
        List<OutChannelInfo> outChannelInfoList=pageBean.getResult();
        List<OutChannelResourceInfo> list=outChannelResourceService.
                getOutChannelResources(outChannelInfoList.stream().map(OutChannelInfo::getOutChannelId).collect(Collectors.toList()));
        //创建poi导出数据对象
        SXSSFWorkbook sxssfWorkbook=new SXSSFWorkbook();
        //创建sheet页
        SXSSFSheet sheet=sxssfWorkbook.createSheet("频道信息表");
        //创建表头
        SXSSFRow headRow=sheet.createRow(0);
        //设置表头信息
        headRow.createCell(0).setCellValue("播出频道ID");
        headRow.createCell(1).setCellValue("名称");
        headRow.createCell(2).setCellValue("类型");
        headRow.createCell(3).setCellValue("内容ID");
        headRow.createCell(4).setCellValue("码率模板");
        headRow.createCell(5).setCellValue("输出地址");
        Map<Long, OutChannelInfo> map=outChannelInfoList.stream().collect(Collectors.toMap(OutChannelInfo::getOutChannelId, Function.identity(),(v1, v2)->v2));
        // 遍历上面数据库查到的数据
        Long outChannelId=null;
        //定义一个值,标记行数
        int count=1;
        //组装数据
        for(OutChannelResourceInfo outChannelResourceInfo:list){
    
    
            SXSSFRow dataRow=sheet.createRow(count);
            if(!outChannelResourceInfo.getOutChannelId().equals(outChannelId)){
    
    
                OutChannelInfo pm=map.get(outChannelResourceInfo.getOutChannelId());
                //id赋值
                outChannelId=outChannelResourceInfo.getOutChannelId();
                //频道信息填入
                dataRow.createCell(0).setCellValue(pm.getOutChannelId());
                dataRow.createCell(1).setCellValue(pm.getName());
                dataRow.createCell(2).setCellValue(getTypeValue().get(pm.getType()));
                dataRow.createCell(3).setCellValue(pm.getContentId());
            }
            dataRow.createCell(4).setCellValue(outChannelResourceInfo.getTpl());
            dataRow.createCell(5).setCellValue(outChannelResourceInfo.getOutUrls());
            count++;
        }
        //筛选出合并行
        int firstRow=1;
        int lastRow;
        //从第二条开始
        Map<Integer, Integer> hbMap=new LinkedHashMap<>();
        for(int i=1;i<list.size();i++){
    
    
            boolean flag=!list.get(i).getOutChannelId().equals(list.get(i-1).getOutChannelId())||i>=list.size()-1;
            if(flag){
    
    
                if(i!=list.size()-1){
    
    
                    lastRow=i;
                }else{
    
    
                    //i+1是因为前面的表头占了一行
                    lastRow=i+1;
                }
                hbMap.put(firstRow,lastRow);
                firstRow=i+1;
            }
        }
        //有一行数据的不进行合并
        for(Map.Entry<Integer, Integer> e:hbMap.entrySet()){
    
    
            for(int i=0;i< 4;i++){
    
    
                if(e.getKey().equals(e.getValue())){
    
    
                    continue;
                }
                CellRangeAddress region2=new CellRangeAddress(e.getKey(),e.getValue(),i,i);
                sheet.addMergedRegion(region2);
            }

        }
        // 下载导出
        String filename="频道信息表";
        // 设置头信息
        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();
    }
Reference link: https://blog.csdn.net/cxy_12345/article/details/103179111

Guess you like

Origin blog.csdn.net/hurtseverywhere/article/details/119725564