首页 > 其他分享 >POI插入行,合并行的单元格

POI插入行,合并行的单元格

时间:2022-12-02 16:45:11浏览次数:39  
标签:index sheet insertRowIndex int 单元格 插入 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);
        		 }
        	 }
         }

  

标签:index,sheet,insertRowIndex,int,单元格,插入,POI
From: https://www.cnblogs.com/wwssgg/p/16944889.html

相关文章