poi动态多行表头导出,及模板导出

public static void main(String[] args) throws IOException, ParseException {

        //数据
        String ownerName = "xxx公司";
        String date = "2022年08月15日";

        SXSSFWorkbook wb = new SXSSFWorkbook();
        //创建一个sheel页
        SXSSFSheet sheet = wb.createSheet("汇总表");
        //设置列宽
        sheet.setDefaultColumnWidth(25);

        //创建一行  设置第一行表头
        Row row1 = sheet.createRow(0);
        sheet.addMergedRegion(new CellRangeAddress(row1.getRowNum(),row1.getRowNum(), row1.getRowNum(), 3));
        for(int i=0;i<=3;i++){
            Cell titleCell = row1.createCell(i);
            if(i == 0){
                titleCell.setCellValue(ownerName + "汇总表");
            }
            titleCell.setCellStyle(createStyle(wb,1));
        }


        //创建第二行表头
        Row row2 = sheet.createRow(1);
        sheet.addMergedRegion(new CellRangeAddress(row2.getRowNum(), row2.getRowNum(), 0, 3));
        for(int i=0;i<=3;i++){
            Cell cell = row2.createCell(i);
            if(i == 0){
                cell.setCellValue(date);
            }
            cell.setCellStyle(createStyle(wb,2));
        }

        //TODO 数据---提取数据
        Map<String, List<Map<String, Object>>> map = new HashMap();
        List<Map<String, Object>> DMSMapList = new ArrayList();
        for (int i = 0; i < 4; i++) {
            Map<String, Object> lm = new HashMap();
            lm.put("alarmTypeName", "类型" + i );
            lm.put("alarmAllNum", i * 100 );
            lm.put("verifyNum", i * 50);
            lm.put("interveneNum", i * 60);
            DMSMapList.add(lm);

        }
        map.put("A", DMSMapList);

        List<Map<String, Object>> ADASMapList = new ArrayList();
        for (int i = 0; i < 4; i++) {
            Map<String, Object> lm = new HashMap();
            lm.put("alarmTypeName", "类型" + i );
            lm.put("alarmAllNum", i * 1000 );
            lm.put("verifyNum", i * 500);
            lm.put("interveneNum", i * 600);
            ADASMapList.add(lm);

        }
        map.put("B", ADASMapList);
        ArrayList<String> alarm_p = Lists.newArrayList("A","B");
        Map<String,String> alarm_p_name = new HashMap();
        alarm_p_name.put("A","类型111");
        alarm_p_name.put("B","类型222");

        //写入数据
        int rowNum = row2.getRowNum();
        for(String s : alarm_p){
            createTitle(wb,sheet, alarm_p_name.get(s) ,rowNum+1);
            rowNum = rowNum + 2;//表头有两行
            List<Map<String, Object>> list = map.get(s);
            if(!CollectionUtils.isEmpty(list)){
                for(Map<String, Object> dataMap : list){
                    Row row = sheet.createRow(rowNum=rowNum+1);
                    Cell cellTemp1 = row.createCell(0);
                    cellTemp1.setCellValue(dataMap.get("alarmTypeName").toString());
                    cellTemp1.setCellStyle(createStyle(wb,4));
                    Cell cellTemp2 = row.createCell(1);
                    cellTemp2.setCellValue(Integer.parseInt(dataMap.get("alarmAllNum").toString()));
                    cellTemp2.setCellStyle(createStyle(wb,0));
                    Cell cellTemp3 = row.createCell(2);
                    cellTemp3.setCellValue(Integer.parseInt(dataMap.get("verifyNum").toString()));
                    cellTemp3.setCellStyle(createStyle(wb,0));
                    Cell cellTemp4 = row.createCell(3);
                    cellTemp4.setCellValue(Integer.parseInt(dataMap.get("interveneNum").toString()));
                    cellTemp4.setCellStyle(createStyle(wb,0));
                }
            }
        }


        // 输出到本地
        String excelName = "D:/excel/myExcel.xls";
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(excelName);
            wb.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    /**
     * 动态 多行表头
     * @param wb
     * @param sheet
     * @param name
     * @param rowNum
     */
    public static void createTitle(SXSSFWorkbook wb, SXSSFSheet sheet,String name ,int rowNum){
        //创建第三行表头
        Row row3 = sheet.createRow(rowNum);
        sheet.addMergedRegion(new CellRangeAddress(row3.getRowNum(), row3.getRowNum()+1, 0, 0));
        Cell row3cell1 = row3.createCell(0);
        row3cell1.setCellValue(name);
        row3cell1.setCellStyle(createStyle(wb,3));

        sheet.addMergedRegion(new CellRangeAddress(row3.getRowNum(), row3.getRowNum(), 1, 2));
        Cell row3cell2 = row3.createCell(1);
        row3cell2.setCellValue("A");
        row3cell2.setCellStyle(createStyle(wb,1));

        sheet.addMergedRegion(new CellRangeAddress(row3.getRowNum(), row3.getRowNum()+1, 3, 3));
        Cell row3cell3 = row3.createCell(3);
        row3cell3.setCellValue("B");
        row3cell3.setCellStyle(createStyle(wb,1));

        //创建第四行表头
        Row row4 = sheet.createRow(rowNum+1);
        Cell row4cell1 = row4.createCell(1);
        row4cell1.setCellValue("C");
        row4cell1.setCellStyle(createStyle(wb,1));

        Cell row4cell2 = row4.createCell(2);
        row4cell2.setCellValue("D");
        row4cell2.setCellStyle(createStyle(wb,1));

        Cell row4cell3 = row4.createCell(3);
        row4cell3.setCellStyle(createStyle(wb,1));
    }

    /**
     * 设置样式
     * @param wb
     * @param num
     * @return
     */
    public static CellStyle createStyle(SXSSFWorkbook wb,int num){

        switch(num){
            case 1 :
                CellStyle style1 = wb.createCellStyle();
                style1.setAlignment(HorizontalAlignment.CENTER);//水平居中
                style1.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
                setBorder(style1);//边框
                Font font = wb.createFont();//字体
                //font.setFontName("Arial");//字号
                font.setBold(true);//加粗
                style1.setFont(font);
                return style1;
            case 2 :
                CellStyle style2 = wb.createCellStyle();
                style2.setAlignment(HorizontalAlignment.RIGHT);//水平靠右
                style2.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
                setBorder(style2);
                return style2;
            case 3 :
                CellStyle style3 = wb.createCellStyle();
                style3.setAlignment(HorizontalAlignment.LEFT);//水平靠左
                style3.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
                setBorder(style3);
                Font font3 = wb.createFont();
                font3.setBold(true);//加粗
                style3.setFont(font3);
                return style3;
            case 4 :
                CellStyle style4 = wb.createCellStyle();
                style4.setAlignment(HorizontalAlignment.LEFT);//水平靠左
                style4.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
                setBorder(style4);
                return style4;
            default :
                CellStyle style = wb.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER);//水平居中
                style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
                setBorder(style);
                return style;
        }
    }

    /**
     * 设置边框
     * @param style
     */
    private static void setBorder(CellStyle style){
        style.setBorderBottom(BorderStyle.THIN); //下边框
        style.setBorderLeft(BorderStyle.THIN);//左边框
        style.setBorderTop(BorderStyle.THIN);//上边框
        style.setBorderRight(BorderStyle.THIN);//右边框
    }

依赖

   <dependency>
      <groupId>cn.afterturn</groupId>
      <artifactId>easypoi-base</artifactId>
      <version>4.1.0</version>
    </dependency>
    <dependency>
      <groupId>cn.afterturn</groupId>
      <artifactId>easypoi-web</artifactId>
      <version>4.1.0</version>
    </dependency>
    <dependency>
      <groupId>cn.afterturn</groupId>
      <artifactId>easypoi-annotation</artifactId>
      <version>4.1.0</version>
    </dependency>

在这里插入图片描述

复杂表格导出,可以使用easypoi的模板导出,我这个有多行动态表头,使用模板导出效果不好
参考官方文档,还有pdf导出,文档导出等等
https://gitee.com/lemur/easypoi

模板导出

直接上demo

List<User> dataList = new ArrayList<>();
        User user1 = new User("张三", 23, 1, 1.73F);
        User user2 = new User("李四", 20, 1, 1.83F);
        User user3 = new User("王五", 25, 2, 1.65F);
        User user4 = new User("小花", 18, 2, 1.65F);
        dataList.add(user1);
        dataList.add(user2);
        dataList.add(user3);
        dataList.add(user4);

        FileOutputStream out = null;
        InputStream templateInputStream = null;
        try {
            // 模板导出 模板地址
            String templatePath = "/excel/template.xlsx"; //resources目录下
            templateInputStream = this.getClass().getResourceAsStream(templatePath);
            // HSSFWorkbook 扩展名xls XSSFWorkbook 扩展名xlsx
            Workbook templateWorkbook = new XSSFWorkbook(templateInputStream);
            //这里不太友好 TemplateExportParams的构造方法竟然没有输入流参数,全都是指定模板url来构造,但我的模板是直接放在项目里的resource目录下的  以jar报形式启动项目 就找不到文件,所以只能先构造一个Workbook 然后set进去
            TemplateExportParams params = new TemplateExportParams("templateUrl", 1);
            params.setTemplateWb(templateWorkbook);
            //数据
            Map<String, Object> map = new HashMap<>();
            map.put("list", dataList);

            //1.直接浏览器下载
            /*response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode("模板导出.xls", "utf-8"));
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            workbook.write(response.getOutputStream());*/

            //2.输出到指定文件夹
            File file =new File("D:/excel");
            //如果文件夹不存在则创建
            if  (!file .exists()  && !file .isDirectory()) {
                file .mkdir();
            }


            // 输出到本地
            String excelName = "D:/excel/myExcel.xlsx";
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            out = new FileOutputStream(excelName);
            workbook.write(out);
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(out !=null){
                try {
                    out.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if(templateInputStream !=null){
                try {
                    templateInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }

在这里插入图片描述

JAVA

/**
     * 将double格式化为指定小数位的String,不足小数位用0补全
     */
    private String roundByScale(Double v, int scale) {
        if(scale <= 0){
            return new DecimalFormat("0").format(v);
        }
        String formatStr = "0.";
        for(int i=0;i<scale;i++){
            formatStr = formatStr + "0";
        }
        return new DecimalFormat(formatStr).format(v);
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中实现多行表头导出Excel可以使用Apache POI库。下面是一个简单的示例代码,其中包括三个表头行和两个数据行: ```java import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExporter { public static void export(String[][] data) throws IOException { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建表头行1 Row headerRow1 = sheet.createRow(0); CellStyle headerStyle1 = workbook.createCellStyle(); headerStyle1.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle1.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置表头行高 headerRow1.setHeightInPoints(30); // 创建表头单元格 for (int i = 0; i < data[0].length; i++) { Cell cell = headerRow1.createCell(i); cell.setCellValue(data[0][i]); cell.setCellStyle(headerStyle1); } // 合并表头行1 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2)); // 创建表头行2 Row headerRow2 = sheet.createRow(1); CellStyle headerStyle2 = workbook.createCellStyle(); headerStyle2.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); headerStyle2.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置表头行高 headerRow2.setHeightInPoints(30); // 创建表头单元格 Cell cell = headerRow2.createCell(0); cell.setCellValue("Header 1"); cell.setCellStyle(headerStyle2); cell = headerRow2.createCell(1); cell.setCellValue("Header 2"); cell.setCellStyle(headerStyle2); cell = headerRow2.createCell(2); cell.setCellValue("Header 3"); cell.setCellStyle(headerStyle2); // 合并表头行2 sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0)); sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2)); // 创建表头行3 Row headerRow3 = sheet.createRow(2); CellStyle headerStyle3 = workbook.createCellStyle(); headerStyle3.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); headerStyle3.setFillPattern(CellStyle.SOLID_FOREGROUND); // 设置表头行高 headerRow3.setHeightInPoints(30); // 创建表头单元格 cell = headerRow3.createCell(1); cell.setCellValue("Sub Header 1"); cell.setCellStyle(headerStyle3); cell = headerRow3.createCell(2); cell.setCellValue("Sub Header 2"); cell.setCellStyle(headerStyle3); // 创建数据行 for (int i = 0; i < data.length - 1; i++) { Row dataRow = sheet.createRow(i + 3); for (int j = 0; j < data[i + 1].length; j++) { Cell dataCell = dataRow.createCell(j); dataCell.setCellValue(data[i + 1][j]); } } // 调整列宽 for (int i = 0; i < data[0].length; i++) { sheet.autoSizeColumn(i); } // 导出Excel文件 FileOutputStream outputStream = new FileOutputStream("output.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); } } ``` 其中,`data`是一个二维数组,第一行是表头,其余行是数据。在代码中,我们创建了三个表头行,分别为“Header 1”、“Header 2”和“Sub Header 1/Sub Header 2”。我们使用`sheet.addMergedRegion`方法将单元格合并以创建多行表头。最后,我们将数据写入Excel文件并导出。你可以根据实际需求修改代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值