1. 程式人生 > >AsposeWords操作表格合併單元格(word已經有的table 列 合併 指定兩個單元格 既可以橫向合併也可以縱向合併)-http://www.xiaoguo123.com/p/aspose_w

AsposeWords操作表格合併單元格(word已經有的table 列 合併 指定兩個單元格 既可以橫向合併也可以縱向合併)-http://www.xiaoguo123.com/p/aspose_w

20180725 親測可以 xjh

強大的AsposeWords for java不僅支援建立表格,還支援合併單元格。今天就簡明扼要記錄下如何實現合併單元格。
大家可以完全套用本文提供的程式碼,只需要提供開始和結束的單元格即可實現合併,無需理解複雜的過程,真是簡潔好用啊。
此程式碼來自官方網站,執行無誤。
先看看合併的效果:

簡單三步實現:
(1)設計一個模板,並確定要合併的開始和結束單元格
(2)呼叫合併單元格mergeCells()函式
(3)輸出合併後word文件。

程式碼如下:

public static void main(String[] args) {
// TODO code application logic here
try{
Document doc = new Document("template.docx");
Table table = (Table) doc.getChild(NodeType.TABLE, 1, true); //第2個表格

// We want to merge the range of cells found in between these two cells.
Cell cellStartRange = table.getRows().get(1).getCells().get(0); //第2行第1列
Cell cellEndRange = table.getRows().get(2).getCells().get(0); //第3行第1列
// Merge all the cells between the two specified cells into one.
mergeCells(cellStartRange, cellEndRange);

cellStartRange = table.getRows().get(3).getCells().get(0); //第4行第1列
cellEndRange = table.getRows().get(5).getCells().get(0); //第6行第1列
// Merge all the cells between the two specified cells into one.
mergeCells(cellStartRange, cellEndRange);

doc.save(“out.docx”);
System.out.println(“Done”);
}
catch(Exception e) {
System.out.println(“error:”+e.getMessage() );
}

}

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

真的簡單明瞭,沒啥好說的。