POI插入行,合并行的单元格
1、POI插入行,合并行的单元格
2、代码
/**
*
* @Title: insertRow
* @Description: TODO 插入行
* @param sheet
* @param insertRowIndex
* @Author:wushigao
* @CreateDate:2022 Mar 17 14:06:05
*/
public static Row insertRow(Sheet sheet,int insertRowIndex) {
if (insertRowIndex <= sheet.getLastRowNum()) {
sheet.shiftRows(insertRowIndex, sheet.getLastRowNum(), 1);
}
int tempRowIndex = insertRowIndex-1;
Row rowTemplate = sheet.getRow(tempRowIndex);
int cellNum = rowTemplate.getLastCellNum() - rowTemplate.getFirstCellNum();
Row insertRow = sheet.createRow(insertRowIndex);
for(int cellIndex=0;cellIndex<cellNum;cellIndex++){
insertRow.createCell(cellIndex);
}
POIUtils.copyCellStyleToRow(rowTemplate,insertRow);
int count = sheet.getNumMergedRegions();
if(count > 0) {
for(int index = 0;index<count;index++) {
CellRangeAddress cellRangeAddress = sheet.getMergedRegion(index);
int firstRow = cellRangeAddress.getFirstRow();
if(firstRow == tempRowIndex) {
CellRangeAddress region = new CellRangeAddress(insertRowIndex, insertRowIndex, cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn()); //起始行,结束行,起始列,结束列
sheet.addMergedRegion(region);
}
}
}
return insertRow;
}
3、复制合并单元格方法
int count = sheet.getNumMergedRegions();
if(count > 0) {
for(int index = 0;index<count;index++) {
CellRangeAddress cellRangeAddress = sheet.getMergedRegion(index);
int firstRow = cellRangeAddress.getFirstRow();
if(firstRow == tempRowIndex) {
CellRangeAddress region = new CellRangeAddress(insertRowIndex, insertRowIndex, cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn()); //起始行,结束行,起始列,结束列
sheet.addMergedRegion(region);
}
}
}

浙公网安备 33010602011771号