基于使用Apache POI库,对excel在目标行索引的后面添加指定行数,且新增行的格式与模板行保持一致

/**
     * excel添加行数:在目标行索引的后面添加指定行数,且新增行的格式与模板行保持一致
     * @example: copyRows(sheet,3,4,5);   已第4行(从0开始计数)为模板行,在第5行(从0开始计数)后新增5行row,且格式与模板行保持一致
     * 
     * @param sheet
     * @param sourceRowIndex    源行的索引
     * @param targetRowIndex    目标行索引
     * @param numberOfRowsToAdd 新增的行数
     * @throws Exception
     */
    public static void copyRows(Sheet sheet, int sourceRowIndex, int targetRowIndex, int numberOfRowsToAdd) {
        Row sourceRow = sheet.getRow(sourceRowIndex);
        if(sourceRow == null) {
            sourceRow = sheet.createRow(sourceRowIndex);
        }
        for (int i = 0; i < numberOfRowsToAdd; i++) {
            sheet.shiftRows(targetRowIndex + i, sheet.getLastRowNum(), 1);
            Row newRow = sheet.createRow(targetRowIndex + i);
            for (int j = 0; j < sourceRow.getLastCellNum(); j++) 
            {
                Cell sourceCell = sourceRow.getCell(j);
                Cell newCell = newRow.createCell(j);
                newCell.setCellStyle(sourceCell.getCellStyle());
                if (sourceCell.getCellType() == CellType.STRING) {
                    newCell.setCellValue(sourceCell.getStringCellValue());
                } else if (sourceCell.getCellType() == CellType.NUMERIC) {
                    newCell.setCellValue(sourceCell.getNumericCellValue());
                } else if (sourceCell.getCellType() == CellType.BOOLEAN) {
                    newCell.setCellValue(sourceCell.getBooleanCellValue());
                } else if (sourceCell.getCellType() == CellType.FORMULA) {
                    newCell.setCellFormula(sourceCell.getCellFormula());
                }
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值