本文指导如何使用 Java 合并 Word 中的单元格。它包含 IDE 设置、步骤列表和示例代码,展示了如何使用 Java 合并 Word 中的表格。它使用预定义方法并展示了如何使用此方法合并目标表中的一系列单元格。
使用 Java 在 Word 中合并单元格的步骤
- 设置环境以使用 Aspose.Words for Java 合并表格单元格
- 将预定义方法mergeCells()添加到您的应用程序
- 加载包含表格的源 Word document
- 从加载的 Word 文件访问目标表
- 创建对要合并的起始和结束单元格的引用
- 调用mergeCells()方法并提供起始和结束单元格
- Save 修改后的 Word 文件
这些步骤定义了如何使用 Java 在 Word 中合并表格。在您的应用程序中添加预定义方法,将源 Word 文件加载到 Document 类对象中,获取目标表的引用,并定义要合并的范围的起始/结束单元格。最后,调用 mergeCells() 方法更新已加载的 Word 文件并将其保存为具有不同名称的新 Word 文件。
使用 Java 合并 Word 表格单元格的代码
import com.aspose.words.*; | |
import java.awt.*; | |
public class Main | |
{ | |
static void mergeCells(Cell startCell, Cell endCell) | |
{ | |
Table parentTable = startCell.getParentRow().getParentTable(); | |
// Define start and ending 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 a range of cells | |
Rectangle range = new Rectangle(Math.min(startCellPos.x, endCellPos.y), Math.min(startCellPos.y, endCellPos.y), | |
Math.abs(endCellPos.x - startCellPos.x) + 1, Math.abs(endCellPos.y - startCellPos.y) + 1); | |
for (Row currentRow : parentTable.getRows()) | |
{ | |
for (Cell cell : currentRow.getCells()) | |
{ | |
Point currentPos = new Point(currentRow.indexOf(cell), parentTable.indexOf(currentRow)); | |
// Validate the current cell | |
if (range.contains(currentPos)) | |
{ | |
cell.getCellFormat().setHorizontalMerge(currentPos.x == range.getX() ? CellMerge.FIRST : CellMerge.PREVIOUS); | |
cell.getCellFormat().setVerticalMerge(currentPos.y == range.getY() ? CellMerge.FIRST : CellMerge.PREVIOUS); | |
} | |
} | |
} | |
} | |
public static void main(String[] args) throws Exception // Merge Table Cells in Java | |
{ | |
// Set the licenses | |
new License().setLicense("License.lic"); | |
Document tableDoc = new Document("Table.docx"); | |
Table tbl = tableDoc.getFirstSection().getBody().getTables().get(1); | |
Cell startingCell = tbl.getRows().get(1).getCells().get(1); | |
Cell endingCell = tbl.getRows().get(2).getCells().get(2); | |
// Merge the cells | |
mergeCells(startingCell, endingCell); | |
tableDoc.save("MergeCells.docx"); | |
System.out.println("Word table merged successfully"); | |
} | |
} |
此代码片段演示了如何使用 Java 在 Microsoft Word 中合并单元格。预定义方法访问父表并设置作为参数提供的范围内所有单元格的水平和垂直合并属性。在您的示例代码中,您无需详细了解此方法,只需使用起始单元格和结束单元格调用 mergeCells() 方法即可。
本教程指导我们如何使用 Java 合并 Word 中的单元格。如果您想按部分拆分 Word 文档,请参阅 使用 Java 将 Word 文档拆分为多个部分 上的文章。