IronWord를 사용하여 C#로 DOCX 파일에 표를 추가하는 방법
IronWord를 사용하면 C# 코드로 Word 문서에 표를 추가할 수 있습니다. 행과 열의 수를 지정하여 Table 객체를 만들고 테두리와 색상으로 서식을 지정한 뒤, 셀에 내용을 채우고 DOCX 파일로 저장합니다.
이 예제에서는 IronWord로 표를 만드는 방법을 보여줍니다. 행과 열의 수를 지정하여 표를 만들고, 서식을 적용한 뒤 내용을 채웁니다. 그런 다음 표를 문서에 삽입하고 저장합니다. 서식이 적용된 표를 포함한 DOCX 파일을 몇 분 안에 생성할 수 있습니다.
-
1IronWord를 NuGet Package Manager로 설치하십시오
-
2다음 코드 조각을 복사하여 실행하세요.
var table = new IronWord.Models.Table(3,4); var doc = new IronWord.WordDocument(); doc.AddTable(table); doc.SaveAs("QuickTable.docx");Dim table As New IronWord.Models.Table(3, 4) Dim doc As New IronWord.WordDocument() doc.AddTable(table) doc.SaveAs("QuickTable.docx")Dim table As New IronWord.Models.Table(3, 4) Dim doc As New IronWord.WordDocument() doc.AddTable(table) doc.SaveAs("QuickTable.docx") -
3실제 운영 환경에서 테스트할 수 있도록 배포하세요.
오늘 프로젝트에서 IronWord 사용을 시작해보세요 무료 체험
기본 작업 절차(5단계)
- DOCX 파일에 표를 추가하는 C# 라이브러리를 다운로드합니다.
- 셀에 내용을 채우고 셀을 모아 행을 구성합니다.
- 행을 추가하여 표를 만듭니다.
- 표를 사용해 새 Word 문서를 초기화한 뒤 표를 추가합니다.
- 최종 Word 문서를 내보냅니다.
Word 문서에 표를 추가하는 방법은 무엇인가요?
표는 Word 문서의 기본 구성 요소입니다. 먼저 행과 열의 수를 지정해 Table 클래스의 인스턴스를 생성합니다. 배경색, 음영, 테두리, 교차 행 음영, 너비 등 표의 서식을 설정합니다. 다음으로 [row, column] 형식으로 각 셀에 접근합니다. 셀에는 텍스트, 이미지, 도형, 단락은 물론 다른 표도 추가할 수 있습니다. 마지막으로 표를 Word 문서에 추가합니다.
IronWord의 표를 사용하면 Word 문서에서 구조화된 데이터를 유연하게 정리할 수 있습니다. 청구서, 보고서 또는 데이터 요약을 작성할 때 Table 클래스로 표의 내용과 표시 방식을 세밀하게 제어할 수 있습니다. 인덱스가 0부터 시작하므로 코드로 셀을 순회하기 쉽고, 다양한 서식 옵션으로 문서의 완성도를 높일 수 있습니다.
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.Style.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");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.Style.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
Dim doc As New WordDocument()
' Create table
Dim table As New Table(5, 3)
' Configure border style
Dim 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.Style.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
' Add table
doc.AddTable(table)
doc.Save("document.docx")Imports IronWord
Imports IronWord.Models
Imports IronWord.Models.Enums
Dim doc As New WordDocument()
' Create table
Dim table As New Table(5, 3)
' Configure border style
Dim 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.Style.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
' Add table
doc.AddTable(table)
doc.Save("document.docx")
TableCell 클래스의 AddChild 메서드는 단락, 이미지, 도형, 표 등 IWordDocumentObject를 구현하는 콘텐츠 객체를 받습니다. 이를 통해 복잡한 문서에서 표 안에 다른 표를 넣을 수 있습니다.
IronWord는 표 셀의 콘텐츠를 관리하는 여러 방법을 제공합니다. 생성자에 초기 콘텐츠를 전달하여 TableCell 인스턴스를 만들거나 AddChild 메서드로 콘텐츠를 하나씩 추가합니다. 서로 다른 콘텐츠 유형을 한 셀에 결합할 수 있습니다. 예를 들어 하나의 셀에 제목 단락과 이미지를 넣고, 그 뒤에 상세 사양을 담은 중첩 표를 추가할 수 있습니다.
다음 예제에서는 표의 셀에 여러 유형의 콘텐츠를 채우는 방법을 보여줍니다.
// Example: Creating cells with mixed content
TableCell complexCell = new TableCell();
// Add a styled paragraph
Paragraph header = new Paragraph();
TextContent headerText = new TextContent("Product Details") { IsBold = true, FontSize = 14 };
header.AddText(headerText);
complexCell.AddChild(header);
// Add multiple text elements
complexCell.AddChild(new TextContent("SKU: "));
complexCell.AddChild(new TextContent("PROD-001") { IsBold = true });
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();
TextContent headerText = new TextContent("Product Details") { IsBold = true, FontSize = 14 };
header.AddText(headerText);
complexCell.AddChild(header);
// Add multiple text elements
complexCell.AddChild(new TextContent("SKU: "));
complexCell.AddChild(new TextContent("PROD-001") { IsBold = true });
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()
Dim headerText As New TextContent("Product Details") With {.IsBold = True, .FontSize = 14}
header.AddText(headerText)
complexCell.AddChild(header)
' Add multiple text elements
complexCell.AddChild(New TextContent("SKU: "))
complexCell.AddChild(New TextContent("PROD-001") With {.IsBold = True})
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' Example: Creating cells with mixed content
Dim complexCell As New TableCell()
' Add a styled paragraph
Dim header As New Paragraph()
Dim headerText As New TextContent("Product Details") With {.IsBold = True, .FontSize = 14}
header.AddText(headerText)
complexCell.AddChild(header)
' Add multiple text elements
complexCell.AddChild(New TextContent("SKU: "))
complexCell.AddChild(New TextContent("PROD-001") With {.IsBold = True})
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와 함께 사용하면 선의 두께를 1/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.Style.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.Style.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
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.Style.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")' 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.Style.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")표의 너비와 정렬 속성으로 레이아웃을 조정할 수 있습니다. 표의 너비를 고정값이나 백분율로 지정하고, 문서 안에서 표를 정렬하거나 주변 콘텐츠와의 배치를 조정할 수 있습니다. 셀별로 배경색, 텍스트 정렬, 안쪽 여백을 지정하여 표의 모양을 세밀하게 제어할 수 있습니다.
이러한 스타일링 옵션을 사용하면 간단한 데이터 표부터 여러 시각적 계층 구조를 가진 복잡한 재무제표에 이르기까지 모든 문서의 디자인 요구 사항에 맞는 표를 만들 수 있습니다.
자주 묻는 질문
C#를 사용하여 DOCX 파일에 테이블을 어떻게 생성할 수 있나요?
IronWord를 사용하여 Table 클래스를 생성함으로써 DOCX 파일에 테이블을 만들 수 있습니다. 스타일과 내용을 설정한 후, WordDocument에 테이블을 추가하고 DOCX 파일로 저장할 수 있습니다.
IronWord에서 사용 가능한 테이블 스타일링 옵션은 무엇인가요?
IronWord는 테이블에 대한 광범위한 스타일링 옵션을 제공하며, 여기에는 테두리, 색상, 셀 패딩, 정렬이 포함됩니다. 조건부 서식, 예를 들어 지그재그 줄무늬를 적용할 수 있으며 BorderValues 열거형에서 다양한 테두리 스타일을 사용하여 테이블 미학을 향상시킬 수 있습니다.
IronWord를 사용하여 개별 테이블 셀에 복잡한 내용을 추가할 수 있나요?
네, IronWord는 AddChild 메소드를 사용하여 개별 테이블 셀에 복잡한 내용을 추가할 수 있습니다. 셀은 중첩된 테이블, 단락, 이미지 및 다양한 텍스트 요소를 포함할 수 있어 다채롭고 상세한 콘텐츠 관리가 가능합니다.
IronWord로 생성된 테이블에 줄무늬 패턴을 어떻게 사용하나요?
테이블에 지그재그 줄무늬를 적용하려면, IronWord의 테이블 스타일의 ZebraColor 속성을 구성하여 가독성과 시각적 매력을 향상시키기 위해 교대로 사용되는 행 색상을 지정합니다.
IronWord를 사용하여 Word 문서에 테이블을 추가하는 단계는 무엇인가요?
IronWord를 사용하여 워드 문서에 테이블을 추가하려면, IronWord 라이브러리를 다운로드하고, 테이블을 생성 및 스타일링 한 후, WordDocument에 삽입하고 문서를 저장해야 합니다.
IronWord에서 테이블의 너비와 정렬을 어떻게 제어하나요?
IronWord에서는 테이블의 너비와 정렬을 테이블의 해당 속성을 설정하여 제어합니다. 이를 통해 정확한 크기나 비율을 지정하고 문서 내에서 테이블을 필요한 대로 정렬할 수 있습니다.
IronWord에서 테이블에 데이터를 채우는 방법은 무엇이 있나요?
IronWord에서는 0 기준 인덱싱과 AddChild 메소드를 사용하여 셀에 TextContent, 이미지 또는 기타 요소를 프로그램matically로 삽입하여 테이블을 채울 수 있습니다.
IronWord는 테이블에 대한 테두리 스타일링을 어떻게 지원하나요?
IronWord는 BorderStyle 클래스를 통해 테두리 색상, 값 및 크기를 사용자 정의할 수 있도록 해 테두리 스타일링을 지원합니다. 이는 테이블의 헤더와 본문 섹션 모두에서 뚜렷한 시각적 계층을 만들 수 있습니다.
IronWord를 사용하여 셀 내에 테이블을 중첩할 수 있나요?
네, IronWord는 AddChild 메소드를 사용하여 셀 내에 테이블을 중첩하는 것을 지원합니다. 이 기능은 복잡한 문서를 위한 정교한 테이블 구조 구축에 도움이 됩니다.
Word 문서에서 테이블을 생성하기 위해 IronWord를 사용하는 장점은 무엇인가요?
IronWord를 사용하여 테이블을 생성하면 문서 구조에 유연하고 프로그래머블한 접근 방식을 제공하여 포괄적인 내용 관리, 세부적인 스타일링 및 전문적인 DOCX 파일을 생성하기 위한 효율적인 자동화를 구현할 수 있습니다.
커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.