1. 程式人生 > 其它 >POI插入行,合併行的單元格

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);
        		 }
        	 }
         }