# C#를 사용하여 MS Word 문서에 테이블에 행 추가하는 방법

# C#를 사용하여 MS Word 문서에 테이블에 행 추가하는 방법

이 튜토리얼에서는 C#를 사용하여 MS Word 문서의 테이블에 라인을 프로그램적으로 추가하는 방법을 배우게됩니다.

Word 문서에서 테이블에 라인을 추가하는 혜택

  • 역동적 인 콘텐츠 관리:- 새 데이터를 맞추기 위해 기존 테이블을 쉽게 수정합니다.

  • 유연성:- 테이블 구조를 수동 편집 없이 프로그래밍으로 조정합니다.

  • 자동화:- 자동 스크립트를 통해 테이블 데이터를 효율적으로 관리합니다.

원제 : Environment Preparation

  • Visual Studio 또는 .NET IDE가 설치되어 있습니다.
  • Aspose.Words 도서관은 NuGet을 통해 사용할 수 있습니다.

단계별 가이드 : Word에서 테이블에 라인을 추가하는 방법

단계 1: Aspose.Words 도서관 설치

NuGet 패키지 관리자를 사용하여 Aspose.Words 패키지를 설치합니다.

Install-Package Aspose.Words

단계 2 : 필요한 이름 공간 수입

프로젝트에 Aspose.Words 및 Aspose.Words.Tables 이름 공간을 포함합니다.

using Aspose.Words;
using Aspose.Words.Tables;

단계 3 : 문서 문서를 열기

기존 MS Word 문서를 다운로드합니다.

Document MSWordDocument = new Document(@"MS Word.docx");

단계 4 : 테이블에 액세스

문서에서 테이블을 인덱스로 얻으십시오.

Table tableToAddRowsTo = MSWordDocument.FirstSection.Body.Tables[0];

단계 5 : 라인을 만들거나 클론

새 줄을 만들거나 테이블에서 기존 하나를 클론합니다.

Row row = new Row(MSWordDocument);

단계 6 : 줄에 세포를 추가합니다.

라인에 셀과 텍스트를 추가합니다.

for (int i = 0; i < 3; i++) 
{
    Cell cell = new Cell(MSWordDocument);
    cell.AppendChild(new Paragraph(MSWordDocument));
    cell.FirstParagraph.Runs.Add(new Run(MSWordDocument, "Text in Cell " + i));
    row.Cells.Add(cell);
}

단계 7 : 끝에 라인을 추가합니다.

RowCollection.Add를 사용하여 테이블에 Rows를 추가합니다.

tableToAddRowsTo.Rows.Add(row);

단계 8 : 특정 인덱스에 라인을 입력합니다.

RowCollection.Insert를 사용하여 특정 인덱스에 라인을 삽입합니다.

tableToAddRowsTo.Rows.Insert(1, row);

단계 9 : 업데이트 된 문서를 저장

추가 라인과 함께 문서를 다시 저장합니다.

MSWordDocument.Save(@"Added Rows to Table in MS Word.docx");

예제 코드는 Word에서 테이블에 라인을 추가합니다.

아래는 테이블에 라인을 추가하는 전체 코드입니다 :

// Open MS Word Document
Document MSWordDocument = new Document(@"input.docx");

// Get the Table by index
Table tableToAddRowsTo = MSWordDocument.FirstSection.Body.Tables[0];

// Create a new Row class object
Row row = new Row(MSWordDocument);

// Add three Cells to Row's cells collection
for (int i = 0; i < 3; i++)
{
    Cell cell = new Cell(MSWordDocument);
    cell.AppendChild(new Paragraph(MSWordDocument));
    cell.FirstParagraph.Runs.Add(new Run(MSWordDocument, "Text in Cell " + i));
    row.Cells.Add(cell);
}

// Insert new Row after the first Row
tableToAddRowsTo.Rows.Insert(1, row);

// Clone an existing Row from Table
Row cloneOfRow = (Row)tableToAddRowsTo.FirstRow.Clone(true);

// Remove all content from all Cells
foreach (Cell cell in cloneOfRow)
{
    cell.RemoveAllChildren();
    cell.EnsureMinimum();
}

// Add multiple empty rows to the end of table
for (int i = 0; i < 10; i++)
{
    Row emptyRow = (Row)cloneOfRow.Clone(true);
    tableToAddRowsTo.Rows.Add(emptyRow);
}

// Save updated document
MSWordDocument.Save(@"output.docx");

결론

이 튜토리얼은 C#를 사용하여 MS Word 문서의 테이블에 라인을 추가하는 방법을 보여줍니다.이 단계를 따르면 Word 문서 내의 테이블을 효과적으로 관리하고 변경할 수 있습니다.

 한국어