1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java doc 合并单元格_AsposeWords操作表格合并单元格

java doc 合并单元格_AsposeWords操作表格合并单元格

时间:2024-03-11 18:52:05

相关推荐

java doc 合并单元格_AsposeWords操作表格合并单元格

强大的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);

}

}

}

}

真的简单明了,没啥好说的。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。