이 문서에서는 Java를 사용하여 Word에서 셀을 병합하는 방법에 대해 설명합니다. IDE 설정, 단계 목록, Java를 사용하여 Word에서 표를 병합하는 방법을 보여주는 샘플 코드가 있습니다. 사전 정의된 메서드를 사용하고 이 메서드를 사용하여 대상 테이블의 셀 범위를 결합하는 방법을 보여줍니다.
Java를 사용하여 Word에서 셀을 결합하는 단계
- Aspose.Words for Java를 사용하여 테이블 셀을 결합하도록 환경을 설정합니다.
- 미리 정의된 메서드 mergeCells()를 애플리케이션에 추가합니다.
- 표가 포함된 소스 Word document을 로드합니다.
- 로드된 Word 파일에서 대상 테이블에 액세스합니다.
- 병합하려는 시작 셀과 종료 셀에 대한 참조를 만듭니다.
- mergeCells() 메서드를 호출하고 시작 셀과 종료 셀을 제공합니다.
- Save 수정된 Word 파일
이 단계는 Java를 사용하여 Word에서 표를 결합하는 방법을 정의합니다. 애플리케이션에 미리 정의된 메서드를 추가하고, 소스 Word 파일을 Document 클래스 객체에 로드하고, 대상 테이블의 참조를 가져오고, 병합하려는 범위의 시작/종료 셀을 정의합니다. 마지막으로, 로드된 Word 파일을 업데이트하고 다른 이름의 새 Word 파일로 저장하는 mergeCells() 메서드를 호출합니다.
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 문서를 섹션으로 분할의 문서를 참조하세요.