/**
* 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());
}
}
}
}