Java使用POI库读取或者生成Excel

发布时间 2023-12-21 13:47:46作者: jiangyang6634
  1. maven引入poi库,版本选4.1.2
    <!-- excel工具 -->
    		<dependency>
    			<groupId>org.apache.poi</groupId>
    			<artifactId>poi-ooxml</artifactId>
    			<version>${poi.version}</version>
    		</dependency>
    

      

  2. 应用,编辑excel有两种方式,一种是使用Excel模板进行读取并进行数据填充的操作,主要是按照模板来写,获取指定行和指定列的数据,然后编辑它
  3. 使用生成的方式,这种方式没有模板文件,需要创建行和创建列,然后编辑这些行和列的数据,还可设计单元格格式和合并单元格操作,注意,使用这种方式需要记录行号,每次生成出一行行号自增

上代码:HSSFCellStyle是设计样式的类,在方法中将表头和列表样式设计好,然后在生成单元格时应用这个样式,从而实现字体大小、加粗、边框等功能。HSSFSheet有很多方法,不一一赘述,详见chatGPT,本质是使用HSSFSheet创建行,而后编辑行和列的操作,尤其是需要遍历出对象列表时,循环遍历会很方便,每次创建行将行号加一即可。合并单元格

sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 9));下标从零开始,对应的是开始行号,结束行号,开始列号,结束列号
/** 第一步,创建一个Workbook,对应一个Excel文件  */
        HSSFWorkbook wb = new HSSFWorkbook();

        /** 第二步,在Workbook中添加一个sheet,对应Excel文件中的sheet  */
        HSSFSheet sheet = wb.createSheet("报表");

        /** 第三步,设置样式以及字体样式*/
        HSSFCellStyle titleStyle = createTitleCellStyle(wb);
        HSSFCellStyle headerStyle = createHeadCellStyle(wb, (short) 10);
        HSSFCellStyle contentStyle = createContentCellStyle(wb, (short) 10);

        sheet.setColumnWidth(0, 10 * 256);
        sheet.setColumnWidth(1, 16 * 256);
        sheet.setColumnWidth(2, 12 * 256);
        sheet.setColumnWidth(3, 10 * 256);
        sheet.setColumnWidth(4, 16 * 256);
        sheet.setColumnWidth(5, 10 * 256);
        sheet.setColumnWidth(6, 11 * 256);
        sheet.setColumnWidth(7, 16 * 256);
        sheet.setColumnWidth(8, 10 * 256);
        sheet.setColumnWidth(9, 13 * 256);
        /** 第四步,创建标题 ,合并标题单元格 */
        // 行号
        int rowNum = 0;
        // 创建第一页的第一行,索引从0开始
        HSSFRow row0 = sheet.createRow(rowNum++);

        row0.setHeight((short) 1200);// 设置行高
        String title = excelData.get("title").toString();
        for (int i = 0; i <= 9; i++) {
            HSSFCell c00 = row0.createCell(i);
            c00.setCellValue(title);
            c00.setCellStyle(titleStyle);
        }
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));//标题合并单元格操作,6为总列数

        // 合并单元格,参数依次为起始行,结束行,起始列,结束列 (索引0开始)
        // 第二行
        HSSFRow row1 = sheet.createRow(rowNum++);
        row1.setHeight((short) 700);

        String[] row_first = {"", "全部车辆维修次数", excelData.get("totalTimes").toString(), "", "全部车辆报价金额", excelData.get("totalSettlementPrice").toString(), "", "全部车辆结算金额", excelData.get("totalPaymentPrice").toString(), ""};
        for (int i = 0; i < row_first.length; i++) {
            HSSFCell tempCell = row1.createCell(i);
            tempCell.setCellValue(row_first[i]);
            tempCell.setCellStyle(headerStyle);
        }

//        // 合并
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 2, 3));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 5, 6));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 8, 9));


        HSSFRow row6 = sheet.createRow(rowNum++);
        row6.setHeight((short) 900);
        String[] row_six = {"分析报告", excelData.get("report").toString(), "", "", "", "", "", "", "", ""};
        for (int i = 0; i < row_six.length; i++) {
            HSSFCell tempCell = row6.createCell(i);
            tempCell.setCellValue(row_six[i]);
            tempCell.setCellStyle(headerStyle);
        }
        // 合并
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 9));

 创建标题样式代码

/**
     * 创建标题样式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle createTitleCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());//背景颜色
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont1.setBold(true); //字体加粗
        headerFont1.setFontName("楷体"); // 设置字体类型
        headerFont1.setFontHeightInPoints((short) 16); // 设置字体大小
        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框
        return cellStyle;
    }

POI也可以通过读取excel来编辑它,适用于特定的表格,不过过程比较繁琐,并且excel不设计好边框会导致读取到了空的单元格,导致编辑失败报错