Java를 사용하여 Word의 테이블에 행을 추가하는 방법

이 짧은 자습서에서는 Java를 사용하여 Word의 테이블에 행을 추가하는 방법을 설명합니다. 이 튜토리얼의 도움으로 Java를 사용하여 Word 테이블에 여러 행을 삽입할 수도 있습니다. 결국 이 출력 파일은 DOCX로 저장되지만 모든 Word 파일 형식으로 저장할 수 있습니다.

Java를 사용하여 Word의 테이블에 행을 추가하는 단계

  1. Maven 저장소에서 Aspose.Words for Java을(를) 추가하도록 프로젝트를 구성합니다.
  2. Document 개체를 사용하여 Table이(가) 포함된 워드 파일을 엽니다.
  3. Word 파일의 테이블에 대한 참조 가져오기
  4. Row을(를) 만들고 열에 원하는 데이터를 추가합니다.
  5. 테이블의 첫 번째 행 뒤에 이 행 삽입
  6. 기존 행 복제 및 내용 지우기
  7. 일부 데이터로 여러 행 채우기
  8. 끝에 Word의 기존 테이블에 행 추가
  9. 기존 테이블에 행 추가 후 파일 저장

이 단계를 사용하여 표가 포함된 Word 파일을 열고 행을 삽입합니다. 마찬가지로 샘플 데이터를 여러 행에 채우고 테이블 끝에 이러한 행을 추가하여 *Java를 사용하여 Word의 테이블에 여러 행을 추가할 수 있습니다.

Java를 사용하여 Word의 테이블에 새 행을 추가하는 코드

import com.aspose.words.License;
import com.aspose.words.Paragraph;
import com.aspose.words.Row;
import com.aspose.words.Run;
import com.aspose.words.Cell;
import com.aspose.words.Document;
import com.aspose.words.Table;
public class HowToAddARowToATableInWordUsingJava {
public static void main() throws Exception { //main() function for HowToAddARowToATableInWordUsingJava
// Instantiate a license to remove trial version watermark in the output Word file
License license = new License();
license.setLicense("Aspose.Words.lic");
// Open Word Document having a table in it
Document WordDocumentWithTable = new Document("MS Word.docx");
// Get the reference to the table by index
Table tableToAddRowsTo = WordDocumentWithTable.getFirstSection().getBody().getTables().get(0);
// Instantiate a new Row class object
Row row = new Row(WordDocumentWithTable);
// Add Cells to the collection of cells of the newly created row
for (int i = 0; i < tableToAddRowsTo.getRows().get(0).getCells().getCount(); i++)
{
Cell cell = new Cell(WordDocumentWithTable);
cell.appendChild(new Paragraph(WordDocumentWithTable));
cell.getFirstParagraph().getRuns().add(new Run(WordDocumentWithTable, "Text in Cell " + i));
row.getCells().add(cell);
}
// Insert the new Row after the first Row in the table
tableToAddRowsTo.getRows().insert(1, row);
// Deep Clone an existing Row from the Table
Row cloneOfRow = (Row)tableToAddRowsTo.getFirstRow().deepClone(true);
// Remove all content from all Cells in the cloned row
for (Cell cell : cloneOfRow)
{
cell.removeAllChildren();
cell.ensureMinimum();
}
// Add number of rows say 10 to the end of table
for (int iRowCount = 0; iRowCount < 10; iRowCount++)//You can set any number of rows instead of 10
{
Row emptyRow = (Row)cloneOfRow.deepClone(true);
tableToAddRowsTo.getRows().add(emptyRow);
}
WordDocumentWithTable.save("Added Rows to Table to MS Word.docx");
}
}

이 Java 코드에서 Document, Table 및 Row 클래스를 사용하여 Word 문서의 다른 요소에 액세스하고 Java를 사용하여 Word의 기존 테이블에 행을 추가했습니다. 코드 끝에서 Java를 사용하여 Word 테이블에 여러 행을 추가하는 샘플이 제공되어 데모 목적으로 루프의 행 컬렉션에 행이 여러 번 추가됩니다.

이 자습서에서는 기존 파일을 열었지만 새 Word 문서를 만들려면 Java를 사용하여 Word 문서를 만드는 방법 문서를 참조하세요. 위의 코드를 실행하기 위해 시스템에서 MS Words 또는 Interop을 사용할 수 있어야 하는 것은 아닙니다.

 한국인