强大的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);
}
}
}
}
真的简单明了,没啥好说的。
1.本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:duhaomu@163.com,我们将第一时间处理!
2.资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。
3.所有资源仅限于参考和学习,版权归原作者所有,更多请阅读网站声明。