aspose合并单元格

工作中遇到处理word模板用到了aspose插件,其中遇到了合并单元格,其中分为上下单元格合并,以及左右单元格合并

1.一行中相邻单元格合并

 //合并所有左右相邻单元格一致的行
		public static void hbCells( HashMap m1,String filepath ) throws Exception{
			
			Map rs=getcf(m1);
			Iterator iterator = rs.keySet().iterator(); 
			 Map rr = new HashMap();
			
			//获取重复数据的合并行的坐标
			 while (iterator.hasNext()){ 
				 Object value = iterator.next(); 
				 List result = (List) rs.get(value); 
				 //System.out.println(result);
				 List list = new ArrayList();
				 List rowlist = new ArrayList();
				 List celllist = new ArrayList();
				
				 for( String js:result){
					
					String jj= getTextCellRow(filepath,js); 
					int row=Integer.parseInt(jj.split(",")[0]);
					int cell=Integer.parseInt(jj.split(",")[1]);
					rowlist.add(row);
					celllist.add(cell);
					
					
				 }
				 list=getCellQJ(rowlist,celllist);
				 if(list.size()>0){
					 rr.put(value, list);
				 }
				   
			 }
			 //2处理合并
			 Iterator ite = rr.keySet().iterator(); 
			 while (ite.hasNext()){ 
				 Object value = ite.next(); 
				 List result = (List) rr.get(value); 
				 hbCell(filepath,result,filepath);
				 }
		}
	
		public static List getCellQJ(List rowList,List cellList) throws Exception{
			 List list = new ArrayList();
			  int maxrow= Collections.max(rowList);
			  int maxcell= Collections.max(cellList);
			  int minrow= Collections.min(rowList);
			  int mincell= Collections.min(cellList);
			  
			  if(maxrow==minrow){
				  int size=rowList.size();
				  int fw=maxcell-mincell+1;
				  //连续的单元格
				  if(size==fw){
					  list.add(mincell+","+minrow);
					  list.add(maxcell+","+minrow);
				  }
				  
			  }
			 return list;
		}
		//合并左右单元
		public static void hbCell( String filepath, List result,String savefile) throws Exception{
			
			int row=Integer.parseInt(result.get(0).split(",")[1]);
			int mincell=Integer.parseInt(result.get(0).split(",")[0]);
			int maxCell=Integer.parseInt(result.get(1).split(",")[0]);
			Document doc = new Document(filepath);
			Table table = (Table) doc.getChild(NodeType.TABLE, 0, true); //第1个表格
			// We want to merge the range of cells found in between these two cells.
			Cell cellStartRange = table.getRows().get(row).getCells().get(mincell); //第2行第1列
			Cell cellEndRange = table.getRows().get(row).getCells().get(maxCell); //第3行第1列
			// Merge all the cells between the two specified cells into one.
			mergeCellshx(cellStartRange, cellEndRange);
			doc.save(savefile);
		}
		//合并一行的相邻单元格
		public static void mergeCellshx(Cell startCell, Cell endCell) {
					Table parentTable = startCell.getParentRow().getParentTable();
					double Cellwidth=0;;
					//Table parentTable2 = endCell.getParentRow().getParentTable();
					// Find the row and cell indices for the start and end cell.
					Point startCellPos = new Point(startCell.getParentRow().indexOf(startCell), parentTable.indexOf(startCell.getParentRow()));
					Point endCellPos = new Point(endCell.getParentRow().indexOf(endCell), parentTable.indexOf(endCell.getParentRow()));
					// Create the range of cells to be merged based off these indices. Inverse each index if the end cell if before the start cell.
					Rectangle mergeRange = new Rectangle(
							Math.min(endCellPos.x, startCellPos.x),
							Math.min(endCellPos.y, endCellPos.y),
							Math.abs(endCellPos.x-startCellPos.x)+1 ,
							1);//1,2,0,18 h,w,x,y
				
					for (Row row : parentTable.getRows()) {
							for (Cell cell : row.getCells()) {
							Point currentPos = new Point(row.indexOf(cell), parentTable.indexOf(row));
				
							// Check if the current cell is inside our merge range then merge it.0,18  1,18
							      if (mergeRange.contains(currentPos)) { 
							    	  Cellwidth+= cell.getCellFormat().getWidth();
											 if (currentPos.y == mergeRange.y)
												cell.getCellFormat().setVerticalMerge(CellMerge.FIRST);
												else
												cell.getCellFormat().setVerticalMerge(CellMerge.NONE);
											 if (currentPos.x==mergeRange.x)
												  cell.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
												  else
												  cell.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
											   
										
									}
							}
						}
					startCell.getCellFormat().setWidth(Cellwidth);
					}

2.处理合并上下单元格

//合并所有上下单元格一致的行
		public static void hbRows( HashMap m1,String filepath ) throws Exception{
			
			Map rs=getcf(m1);
			Iterator iterator = rs.keySet().iterator(); 
			 Map rr = new HashMap();
			 Map cr = new HashMap();
			//获取重复数据的合并行的坐标
			 while (iterator.hasNext()){ 
				 Object value = iterator.next(); 
				 List result = (List) rs.get(value); 
				 //System.out.println(result);
				 List listr = new ArrayList();
				 List listc = new ArrayList();
				 List rowlist = new ArrayList();
				 List celllist = new ArrayList();
				
				 for( String js:result){
					
					String jj= getTextCellRow(filepath,js); 
					if(StringUtils.isNotEmpty(jj)){
						int row=Integer.parseInt(jj.split(",")[0]);
						int cell=Integer.parseInt(jj.split(",")[1]);
						rowlist.add(row);
						celllist.add(cell);
					}
					
					
					
				 }
				 if(rowlist.size()>0){
					 listr=getRowQJ(rowlist,celllist);
					 if(listr.size()>0){
						 rr.put(value, listr);
					 }
					 listc=getCellQJ(rowlist,celllist);
					 if(listc.size()>0){
						 cr.put(value, listc);
					 }
				 }
				
				   
			 }
			 //2处理合并
			 //1.合并上下相同的单元格
			 Iterator ite = rr.keySet().iterator(); 
			 while (ite.hasNext()){ 
				 Object value = ite.next(); 
				 List result = (List) rr.get(value); 
				 hbRow(filepath,result,filepath);
				 }
			 //2.合并左右相同的单元格
			  Iterator itc = cr.keySet().iterator(); 
			  while (itc.hasNext()){ 
				 Object value = itc.next(); 
				 List result = (List) cr.get(value); 
				 hbCell(filepath,result,filepath);
				 }
		}
		//合并上下单元
		public static void hbRow( String filepath, List result,String savefile) throws Exception{
			
			int minrow=Integer.parseInt(result.get(0).split(",")[0]);
			int cell=Integer.parseInt(result.get(0).split(",")[1]);
			int maxrow=Integer.parseInt(result.get(1).split(",")[0]);
			Document doc = new Document(filepath);
			Table table = (Table) doc.getChild(NodeType.TABLE, 0, true); //第1个表格
			// We want to merge the range of cells found in between these two cells.
			Cell cellStartRange = table.getRows().get(minrow).getCells().get(cell); //第2行第1列
			Cell cellEndRange = table.getRows().get(maxrow).getCells().get(cell); //第3行第1列
			// Merge all the cells between the two specified cells into one.
			mergeCells(cellStartRange, cellEndRange);
			doc.save(savefile);
		}
		//获取区间row大小必须列一致
		public static List getRowQJ(List rowList,List cellList) throws Exception{
			 List list = new ArrayList();
			  int maxrow= Collections.max(rowList);
			  int maxcell= Collections.max(cellList);
			  int minrow= Collections.min(rowList);
			  int mincell= Collections.min(cellList);
			  
			  if(maxcell==mincell){
				  int size=rowList.size();
				  int fw=maxrow-minrow+1;
				  //连续的单元格
				  if(size==fw){
					  //只有第一列
					  if(mincell==0){
						  list.add(minrow+","+mincell);
						  list.add(maxrow+","+mincell);
					  }

				  }
				  
			  }
			 return list;
		}
		//获取相同value的key
		 public static Map getcf(Map map){
			 Map rs = new HashMap();
			 Map values = new HashMap();
			 List list = new ArrayList(); 
			 Iterator iterator = map.keySet().iterator(); 
			 while (iterator.hasNext()) { 
			 Object key = iterator.next(); 
			 Object value = map.get(key); 
			 if (map.containsValue(value)) { 
			 if (values.containsKey(value)) { 
			 list = (List) values.get(value); 
			 } else { 
			 list = new ArrayList(); 
			 } 
			 list.add(key); 
			 values.put(value, list); 
			 } 
			 } 

			
			 iterator = values.keySet().iterator(); 
			 while (iterator.hasNext()) { 
			 Object value = iterator.next(); 
			 List result = (List) values.get(value); 
			 if (result.size() > 1) { 
				 rs.put(value, result);
				// System.out.println("value :" + value + "  -> keys:" + result.toString()); 
				 } 
			 } 
			
			return rs;	
		  }
	   //获取内容的行列
		public static String getTextCellRow(String FilePath,String data) throws Exception{
			Document doc;
			String tt="";
			String s = "Aspose.Total for JavaAspose.Words for JavaEnterprise20991231209912318bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=";
	    	ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
	    	License license = new License();
	    	license.setLicense(is);
			doc = new Document(FilePath);
			//替换表格
	        //获取第一个表格
			Table table = (Table)doc.getChild(NodeType.TABLE, 0, true);
			
	   if(table!=null){
		   DocumentBuilder builder = new DocumentBuilder(doc);
			RowCollection rows = table.getRows();
//			System.out.println("rows==="+rows.getCount());
			for (int i = 0; i < rows.getCount(); i++) {
				Row row = rows.get(i);
				for(int j=0; j

3测试方法

合并map中value值相同的相邻单元格

 String filepath="E://AAA//1.doc";

            HashMap m1 = new HashMap();
            m1.put("1","黄");
            m1.put("11","黄");
            m1.put("3","涛");
            m1.put("4","涛");
            hbCells(m1,filepath);
            hbRows(m1,filepath);

4.文件的表格样式

aspose合并单元格_第1张图片

5.合并之后

 aspose合并单元格_第2张图片

 

 

你可能感兴趣的:(java,aspose)