aspose合并单元格

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

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

 //合并所有左右相邻单元格一致的行
		public static void hbCells( HashMap<String,Object> 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<String> result = (List) rs.get(value); 
				 //System.out.println(result);
				 List list = new ArrayList();
				 List<Integer> rowlist = new ArrayList<Integer>();
				 List<Integer> celllist = new ArrayList<Integer>();
				
				 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<String> result = (List) rr.get(value); 
				 hbCell(filepath,result,filepath);
				 }
		}
	
		public static List<String> getCellQJ(List<Integer> rowList,List<Integer> cellList) throws Exception{
			 List<String> list = new ArrayList<String>();
			  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<String> 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<String,Object> 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<String> result = (List) rs.get(value); 
				 //System.out.println(result);
				 List listr = new ArrayList();
				 List listc = new ArrayList();
				 List<Integer> rowlist = new ArrayList<Integer>();
				 List<Integer> celllist = new ArrayList<Integer>();
				
				 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<String> result = (List) rr.get(value); 
				 hbRow(filepath,result,filepath);
				 }
			 //2.合并左右相同的单元格
			  Iterator itc = cr.keySet().iterator(); 
			  while (itc.hasNext()){ 
				 Object value = itc.next(); 
				 List<String> result = (List) cr.get(value); 
				 hbCell(filepath,result,filepath);
				 }
		}
		//合并上下单元
		public static void hbRow( String filepath, List<String> 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<String> getRowQJ(List<Integer> rowList,List<Integer> cellList) throws Exception{
			 List<String> list = new ArrayList<String>();
			  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<String, Object> 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 = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
	    	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<row.getCells().getCount(); j++){
					Cell cell=row.getCells().get(j);
					if(null != cell ){
						String text = cell.getText().trim();
						if(null != text && !"".equals(text)){
		                   if(text.equals(data)){
		                	   tt=i+","+j;
		                   }
						 }					
						}
				  }
				}
				
			}
	   
			return tt;

		}
  /**合并列
	* Merges the range of cells found between the two specified cells both
	* horizontally and vertically. Can span over multiple rows.
	* @param startCell
	* @param endCell
	*/
	public static void mergeCells(Cell startCell, Cell endCell) {
	Table parentTable = startCell.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(startCellPos.x, endCellPos.x), Math.min(startCellPos.y, endCellPos.y), Math.abs(endCellPos.x-startCellPos.x) + 1,
	Math.abs(endCellPos.y-startCellPos.y) + 1);
	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.
			if (mergeRange.contains(currentPos)) {
					if (currentPos.x==mergeRange.x)
					cell.getCellFormat().setHorizontalMerge(CellMerge.FIRST);
					else
					cell.getCellFormat().setHorizontalMerge(CellMerge.PREVIOUS);
		
					if (currentPos.y == mergeRange.y)
					cell.getCellFormat().setVerticalMerge(CellMerge.FIRST);
					else
					cell.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
					}
			}
		}
	}

3测试方法

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

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

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

4.文件的表格样式

5.合并之后

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在使用Aspose进行表格操作时,可以通过使用合并单元格方法来合并单元格。以下是使用Spring Boot和Aspose的示例代码: 1. 首先,确保已将Aspose依赖项添加到项目的pom.xml文件中: ```xml <dependency> <groupId>com.aspose</groupId> <artifactId>aspose-words</artifactId> <version>20.10</version> </dependency> ``` 2. 创建一个处理表格的方法,其中包括合并单元格的代码: ```java import com.aspose.words.Document; import com.aspose.words.Node; import com.aspose.words.NodeType; import com.aspose.words.Table; import com.aspose.words.TableRow; // ... public class TableUtils { public void mergeCells(Document doc, int tableIndex, int fromRow, int fromCell, int toRow, int toCell) { Table table = (Table) doc.getChild(NodeType.TABLE, tableIndex, true); for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) { TableRow row = table.getRows().get(rowIndex); for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) { row.getCells().get(cellIndex).getCellFormat().setHorizontalMerge(CellMerge.FIRST); if (cellIndex == fromCell) { row.getCells().get(cellIndex).getCellFormat().setVerticalMerge(CellMerge.FIRST); } else { row.getCells().get(cellIndex).remove(); } } } } } ``` 3. 在Spring Boot应用程序中调用该方法来处理表格并合并单元格: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); // Load the document Document doc = new Document("path/to/your/document.docx"); TableUtils tableUtils = new TableUtils(); tableUtils.mergeCells(doc, 0, 0, 0, 1, 1); // 合并第一个表格的左上角两个单元格 // Save the document doc.save("path/to/save/modified_document.docx"); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值