IronWord 사용하여 C#으로 DOCX 파일에 표를 추가하는 방법
IronWord를 사용하면 개발자가 C#을 통해 Word 문서에 테이블을 프로그래밍 방식으로 추가할 수 있습니다. 이는 지정된 행과 열을 가진 Table 객체를 생성하고, 테두리와 색상으로 스타일을 지정하며, 셀에 내용을 채운 후 DOCX 파일로 저장하는 방식으로 이루어집니다.
빠른 시작: 한 번의 호출로 테이블 생성 및 저장
이 예제는 IronWord 에서 테이블을 만드는 방법을 보여줍니다. 치수를 지정하여 표를 만들고, 스타일을 적용하고, 내용을 추가하고, 문서에 삽입한 다음 저장합니다. 스타일이 적용된 표가 포함된 DOCX 파일을 몇 분 안에 생성할 수 있습니다.
-
NuGet 패키지 관리자를 사용하여 https://www.nuget.org/packages/IronWord 설치하기
PM > Install-Package IronWord -
다음 코드 조각을 복사하여 실행하세요.
var table = new IronWord.Models.Table(3,4); var doc = new IronWord.WordDocument(); doc.AddTable(table); doc.SaveAs("QuickTable.docx"); -
실제 운영 환경에서 테스트할 수 있도록 배포하세요.
무료 체험판으로 오늘 프로젝트에서 IronWord 사용 시작하기
최소 워크플로우(5단계)
- DOCX 파일에 표를 추가하는 C# 라이브러리를 다운로드하세요.
- 각 셀에 내용을 입력하고 셀들을 모아서 행을 만듭니다.
- 행을 추가하여 테이블을 만드세요
- 새 Word 문서를 만들고 표와 해당 표를 추가합니다.
- 최종 Word 문서를 내보냅니다.
워드 문서에 표를 추가하는 방법은 무엇인가요?
표는 워드 문서의 기본 구성 요소입니다. 먼저, 행과 열의 수를 지정하여 Table 클래스를 인스턴스화합니다. 배경색, 음영, 테두리, 줄무늬, 너비 등 테이블의 스타일을 구성하세요. 둘째, 직관적인 [row, column] 인덱싱을 사용하여 각 셀에 접근합니다. 각 셀에 텍스트, 이미지, 도형, 단락 또는 표를 추가할 수 있습니다. 마지막으로, 표를 워드 문서에 추가하세요.
IronWord 의 표는 Word 문서에서 구조화된 데이터를 구성하기 위한 유연한 기반을 제공합니다. 인보이스, 보고서 또는 데이터 요약서를 생성할 때, Table 클래스는 콘텐츠와 표시 형식을 포괄적으로 제어할 수 있는 기능을 제공합니다. 제로 기반 인덱싱 시스템은 프로그래밍 셀 반복을 간소화하며, 풍부한 스타일링 옵션은 전문가다운 외관을 보장합니다.
:path=/static-assets/word/content-code-examples/how-to/add-table-add-table.cs
using IronWord;
using IronWord.Models;
using IronWord.Models.Enums;
WordDocument doc = new WordDocument();
// Create table
Table table = new Table(5, 3);
// Configure border style
BorderStyle borderStyle = new BorderStyle();
borderStyle.BorderColor = Color.Black;
borderStyle.BorderValue = BorderValues.Thick;
borderStyle.BorderSize = 5;
// Configure table border
TableBorders tableBorders = new TableBorders()
{
TopBorder = borderStyle,
RightBorder = borderStyle,
BottomBorder = borderStyle,
LeftBorder = borderStyle,
};
// Apply styling
table.Zebra = new ZebraColor("FFFFFF", "dddddd");
table.Borders = tableBorders;
// Populate table
table[0, 0] = new TableCell(new TextContent("Number"));
table[0, 1] = new TableCell(new TextContent("First Name"));
table[0, 2] = new TableCell(new TextContent("Last Name"));
for (int i = 1; i < table.Rows.Count; i++)
{
table[i, 0].AddChild(new TextContent($"{i}"));
table[i, 1].AddChild(new TextContent($"---"));
table[i, 2].AddChild(new TextContent($"---"));
}
// Add table
doc.AddTable(table);
doc.Save("document.docx");
Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums
Private doc As New WordDocument()
' Create table
Private table As New Table(5, 3)
' Configure border style
Private borderStyle As New BorderStyle()
borderStyle.BorderColor = Color.Black
borderStyle.BorderValue = BorderValues.Thick
borderStyle.BorderSize = 5
' Configure table border
Dim tableBorders As New TableBorders() With {
.TopBorder = borderStyle,
.RightBorder = borderStyle,
.BottomBorder = borderStyle,
.LeftBorder = borderStyle
}
' Apply styling
table.Zebra = New ZebraColor("FFFFFF", "dddddd")
table.Borders = tableBorders
' Populate table
table(0, 0) = New TableCell(New TextContent("Number"))
table(0, 1) = New TableCell(New TextContent("First Name"))
table(0, 2) = New TableCell(New TextContent("Last Name"))
For i As Integer = 1 To table.Rows.Count - 1
table(i, 0).AddChild(New TextContent($"{i}"))
table(i, 1).AddChild(New TextContent($"---"))
table(i, 2).AddChild(New TextContent($"---"))
Next i
' Add table
doc.AddTable(table)
doc.Save("document.docx")
AddChild 클래스의 TableCell 메서드는 단락, 이미지, 도형 및 표를 포함하는 ContentElement 객체를 매개변수로 받습니다. 이를 통해 복잡한 사용 사례를 위해 중첩 테이블을 사용할 수 있습니다.
IronWord 테이블 셀 작업 시 콘텐츠 관리를 위한 다양한 방법을 제공합니다. 생성자를 사용하여 초기 콘텐츠와 함께 TableCell를 인스턴스화하거나, AddChild 메서드를 사용하여 콘텐츠를 점진적으로 추가하십시오. 이러한 유연성을 통해 다양한 콘텐츠 유형을 결합한 복잡한 셀 구조를 구축할 수 있습니다. 예를 들어, 하나의 셀에 제목 단락, 이미지, 그리고 상세 사양을 위한 중첩된 표가 포함될 수 있습니다.
다음은 고급 세포 증식 기술을 보여주는 예입니다.
// Example: Creating cells with mixed content
TableCell complexCell = new TableCell();
// Add a styled paragraph
Paragraph header = new Paragraph();
header.Add(new TextContent("Product Details").Bold().FontSize = 14);
complexCell.AddChild(header);
// Add multiple text elements
complexCell.AddChild(new TextContent("SKU: "));
complexCell.AddChild(new TextContent("PROD-001").Bold());
complexCell.AddChild(new TextContent("\nPrice: $49.99"));
// Cells can also contain lists, images, and more
// This demonstrates the versatility of table cells in IronWord
// Example: Creating cells with mixed content
TableCell complexCell = new TableCell();
// Add a styled paragraph
Paragraph header = new Paragraph();
header.Add(new TextContent("Product Details").Bold().FontSize = 14);
complexCell.AddChild(header);
// Add multiple text elements
complexCell.AddChild(new TextContent("SKU: "));
complexCell.AddChild(new TextContent("PROD-001").Bold());
complexCell.AddChild(new TextContent("\nPrice: $49.99"));
// Cells can also contain lists, images, and more
// This demonstrates the versatility of table cells in IronWord
' Example: Creating cells with mixed content
Dim complexCell As New TableCell()
' Add a styled paragraph
Dim header As New Paragraph()
header.Add(New TextContent("Product Details").Bold().FontSize = 14)
complexCell.AddChild(header)
' Add multiple text elements
complexCell.AddChild(New TextContent("SKU: "))
complexCell.AddChild(New TextContent("PROD-001").Bold())
complexCell.AddChild(New TextContent(vbCrLf & "Price: $49.99"))
' Cells can also contain lists, images, and more
' This demonstrates the versatility of table cells in IronWord
테이블에 적용할 수 있는 스타일링 옵션은 무엇인가요?
IronWord 표에 대한 광범위한 스타일링 기능을 제공하여 시각적으로 매력적이고 전문적인 문서를 만들 수 있도록 합니다. 기본 테두리와 색상 외에도 셀 여백, 정렬을 제어하고 얼룩말 무늬를 통해 조건부 서식을 적용할 수 있습니다. 이 스타일링 시스템은 친숙한 속성 이름과 명확한 값 열거형을 사용하여 강력한 기능과 직관적인 디자인을 결합합니다.
사용 가능한 테두리 스타일은 무엇인가요?
BorderValues 열거형을 사용하여 경계 값에 대해 사용 가능한 모든 옵션을 확인하십시오:
BorderValues 열거형은 테이블의 미적 요소를 위한 포괄적인 옵션을 제공합니다. 단순한 단선부터 물결이나 점과 같은 복잡한 패턴에 이르기까지, 각 스타일은 특정한 디자인 목적을 가지고 있습니다. 업무용 문서에는 전문적인 느낌의 이중 또는 삼중 테두리가 적합하며, 창의적인 문서에는 물결무늬 또는 점선 무늬가 활용될 수 있습니다. BorderSize 속성은 BorderValue와 함께 작동하여 8포인트 단위로 측정되는 선 두께를 정밀하게 제어할 수 있게 해줍니다.
다음은 다양한 테두리 구성 방식을 보여주는 실제 사례입니다.
// Example: Applying different borders to table sections
Table styledTable = new Table(4, 4);
// Create distinct border styles for header and body
BorderStyle headerBorder = new BorderStyle
{
BorderColor = Color.Navy,
BorderValue = BorderValues.Double,
BorderSize = 8
};
BorderStyle bodyBorder = new BorderStyle
{
BorderColor = Color.Gray,
BorderValue = BorderValues.Dotted,
BorderSize = 3
};
// Apply different borders to different parts of the table
// This creates visual hierarchy and improves readability
styledTable.Borders = new TableBorders
{
TopBorder = headerBorder,
BottomBorder = headerBorder,
LeftBorder = bodyBorder,
RightBorder = bodyBorder,
InsideHorizontalBorder = bodyBorder,
InsideVerticalBorder = bodyBorder
};
// Zebra striping for better row distinction
styledTable.Zebra = new ZebraColor("F5F5F5", "FFFFFF");
// Example: Applying different borders to table sections
Table styledTable = new Table(4, 4);
// Create distinct border styles for header and body
BorderStyle headerBorder = new BorderStyle
{
BorderColor = Color.Navy,
BorderValue = BorderValues.Double,
BorderSize = 8
};
BorderStyle bodyBorder = new BorderStyle
{
BorderColor = Color.Gray,
BorderValue = BorderValues.Dotted,
BorderSize = 3
};
// Apply different borders to different parts of the table
// This creates visual hierarchy and improves readability
styledTable.Borders = new TableBorders
{
TopBorder = headerBorder,
BottomBorder = headerBorder,
LeftBorder = bodyBorder,
RightBorder = bodyBorder,
InsideHorizontalBorder = bodyBorder,
InsideVerticalBorder = bodyBorder
};
// Zebra striping for better row distinction
styledTable.Zebra = new ZebraColor("F5F5F5", "FFFFFF");
Imports System.Drawing
' Example: Applying different borders to table sections
Dim styledTable As New Table(4, 4)
' Create distinct border styles for header and body
Dim headerBorder As New BorderStyle With {
.BorderColor = Color.Navy,
.BorderValue = BorderValues.Double,
.BorderSize = 8
}
Dim bodyBorder As New BorderStyle With {
.BorderColor = Color.Gray,
.BorderValue = BorderValues.Dotted,
.BorderSize = 3
}
' Apply different borders to different parts of the table
' This creates visual hierarchy and improves readability
styledTable.Borders = New TableBorders With {
.TopBorder = headerBorder,
.BottomBorder = headerBorder,
.LeftBorder = bodyBorder,
.RightBorder = bodyBorder,
.InsideHorizontalBorder = bodyBorder,
.InsideVerticalBorder = bodyBorder
}
' Zebra striping for better row distinction
styledTable.Zebra = New ZebraColor("F5F5F5", "FFFFFF")
테이블 너비 및 정렬 속성은 추가적인 레이아웃 제어 기능을 제공합니다. 표의 너비나 비율을 특정 값으로 설정하고, 문서 내에서 표를 정렬하고, 주변 콘텐츠와의 상호 작용을 제어할 수 있습니다. 셀 수준 스타일링 옵션에는 개별 배경색, 텍스트 정렬 및 여백 조정이 포함되어 테이블 모양의 모든 측면을 세밀하게 제어할 수 있습니다.
이러한 스타일링 옵션을 사용하면 간단한 데이터 표부터 여러 시각적 계층 구조를 가진 복잡한 재무제표에 이르기까지 모든 문서의 디자인 요구 사항에 맞는 표를 만들 수 있습니다.
자주 묻는 질문
Word 문서에서 특정 크기의 테이블을 어떻게 만드나요?
IronWord를 사용하여 Table 클래스를 인스턴스화하고 행과 열의 수를 지정하여 테이블을 만들 수 있습니다. 예를 들어, 'var table = new IronWord.Models.Table(3,4);'을 사용하여 3행 4열 테이블을 만드세요. 그런 다음 WordDocument 객체에 추가하고 DOCX 파일로 저장하세요.
테두리와 색상으로 테이블 스타일을 프로그래밍 방식으로 지정할 수 있나요?
네, IronWord에서는 배경색, 음영, 테두리, 지브라 스트라이프 및 너비 등을 포함하여 포괄적인 테이블 스타일을 구성할 수 있습니다. 이러한 스타일을 Table 객체에 적용한 후 Word 문서에 추가할 수 있습니다.
테이블의 특정 셀을 어떻게 접근하고 채울 수 있나요?
IronWord는 테이블 셀에 액세스하기 위해 0 기반 인덱싱을 사용합니다. 직관적인 [행, 열] 표기법을 사용하여 셀에 액세스한 다음, 텍스트, 이미지, 도형, 단락 또는 심지어 중첩 테이블과 같은 다양한 콘텐츠 타입으로 채울 수 있습니다.
테이블 셀에 어떤 종류의 콘텐츠를 추가할 수 있나요?
IronWord의 TableCell 클래스를 사용하여 ContentElement 객체를 받는 AddChild 메서드를 통해 여러 콘텐츠 타입을 추가할 수 있습니다. 여기에는 단락, 이미지, 도형, 심지어 중첩 테이블도 포함되며 테이블 구조를 만들 수 있습니다.
테이블 셀 내에 중첩 테이블을 생성할 수 있나요?
네, IronWord는 중첩 테이블을 지원합니다. AddChild 메서드는 테이블을 포함하는 ContentElement 객체를 허용하므로 복잡한 데이터 조직 요구사항을 처리하기 위해 테이블 셀 내에 테이블을 추가할 수 있습니다.
테이블이 있는 DOCX 파일을 생성하는 가장 빠른 방법은 무엇인가요?
IronWord와 함께 가장 빠른 방법은 테이블 객체의 크기를 설정하고, WordDocument를 인스턴스화하고, AddTable() 함수로 테이블을 추가하고 SaveAs() 함수로 저장하는 것입니다. 이 전체 과정을 단 4줄의 코드로 완료할 수 있습니다.

