aspose Word实现表格合并

/**
     * 合并单元格
	 * @throws Exception 
     */
	public static void mergeCellsForPurchaseResult(String saveFilePath) throws Exception {
		// 得到word对象及word中需要合并行的表格对象
		Document doc = new Document(saveFilePath);
		Table table = (Table) doc.getChild(NodeType.TABLE, 0, true);
        
        // 定义合并行的开始行、开始列、结束列
        int startRowNum = 6;
        int startCellNum = 1;
        int endCellNum = 3;

        RowCollection rows = table.getRows();
        // 循环行列处理数据进行表格合并
		for (int i = startRowNum; i <= rows.getCount(); i++){
			// 当前列当前行对象、当前列上一行对象
			Cell cellStartRange = table.getRows().get(i).getCells().get(startCellNum);
			Cell cellEndRange = table.getRows().get(i-1).getCells().get(startCellNum);
			// 当前行对象和上一行对象不相等时,则合并单元格
			if(!cellStartRange.getText().equals(cellEndRange.getText()) && i > startRowNum){
				for (int j = startCellNum; j <= endCellNum; j++){
					mergeCells(rows.get(startRowNum).getCells().get(j), rows.get(i-1).getCells().get(j),table);
					doc.save(saveFilePath, SaveFormat.DOC);
				}
				startRowNum = i;
			}
			
			// 上一列当前行对象用于判断什么时候结束表格合并(代表word文档中的回车符)
			Cell endRange = table.getRows().get(i).getCells().get(startCellNum-1);
			if("采购代表".equals(endRange.getText())){
				return;
			}
		}
	}
	
	/**
	 * 合并单元格
	 * @param startCell 开始单元格
	 * @param endCell 结束单元格
	 * @param table 表格
	 */
	public static void mergeCells(Cell startCell, Cell endCell, Table table) {
		Point startCellPos = new Point(startCell.getParentRow().indexOf(startCell), table.indexOf(startCell.getParentRow()));
		Point endCellPos = new Point(endCell.getParentRow().indexOf(endCell), table.indexOf(endCell.getParentRow()));
		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 : table.getRows()) {
			for (Cell cell : row.getCells()) {
				Point currentPos = new Point(row.indexOf(cell), table.indexOf(row));
				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);
					}	
				}
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/zy123698745/article/details/85319845