C#에서 Word 템플릿을 사용하여 Word 문서를 생성하는 방법
현대 응용프로그램에서는 청구서, 송장, 편지 등 다양한 목적을 위해 즉석에서 Word 문서를 생성하는 것이 중요합니다. Microsoft Word 템플릿 문서 기능은 일관성과 효율성을 보장하는 강력한 방법을 제공합니다. 하지만 이러한 템플릿을 수동으로 채우는 것은 시간 소모적이고 오류가 발생할 수 있습니다. Iron Software에서 제공하는 IronWord가 바로 그 해결책입니다. 이는 .NET 라이브러리로 Word 템플릿을 프로그램적으로 채우는 과정을 자동화하도록 설계되었습니다. 이 기사에서는 IronWord를 사용하여 Word 문서 템플릿을 채우는 방법과 이 과정을 설명하는 실제 예제를 제공합니다.
C#에서 Word 템플릿을 사용하여 Word 문서를 생성하는 방법
- Microsoft Visual Studio에서 새 프로젝트를 만듭니다.
- NuGet 패키지 관리자를 통해 IronWord를 설치하십시오.
- Word 템플릿 문서를 생성합니다.
- Word 문서에 데이터를 삽입하고 새 파일로 저장합니다.
- 생성된 Word 문서에 텍스트 효과를 추가합니다.
IronWord란?
Iron Software에서 제공하는 IronWord는 Microsoft Word 문서의 생성, 조작 및 관리를 프로그래밍 방식으로 용이하게 하는 .NET 라이브러리입니다. 개발자가 Word 문서 생성 프로세스를 자동화할 수 있도록 하여 애플리케이션 내에서 보고서, 송장, 편지 및 기타 유형의 문서를 동적으로 생성하기 쉽게 만듭니다.
IronWord의 주요 기능
1. C#로 Word 템플릿 채우기 및 처리
IronWord는 템플릿 문서에서 자리 표시자를 정의하고 런타임에 실제 데이터로 교체할 수 있도록 하는 Word 템플릿 사용을 가능하게 합니다.
2. 텍스트 조작
Word 문서 내에 텍스트를 쉽게 삽입, 교체 또는 삭제할 수 있습니다.
3. 서식
라이브러리는 글꼴 스타일, 크기, 색상 및 단락 정렬을 포함한 다양한 서식 옵션을 지원합니다.
4. 표 및 이미지
IronWord를 사용하여 문서 내에서 표와 이미지를 삽입하고 조작할 수 있습니다.
5. 호환성
다양한 버전의 Microsoft Word와 원활하게 작동하여 호환성과 사용의 용이성을 보장합니다.
사용 사례
- 보고서 생성: 동적 데이터를 통해 상세 보고서를 자동으로 생성하십시오.
- 송장 생성: 고객 및 거래 세부 정보를 채워 전문적인 송장을 만듭니다.
- 계약 관리: 개인화된 정보로 계약을 자동으로 생성합니다.
- 편지 및 공지: 고객이나 직원에게 개인 맞춤형 편지 및 공지를 생성합니다.
IronWord는 .NET 애플리케이션에서 Word 문서 작업을 간소화하여 문서 생성 및 관리 작업을 자동화하려는 개발자에게 유용한 도구입니다.
필수 조건
다음을 준비했는지 다시 한 번 확인하시기 바랍니다:
- Visual Studio가 컴퓨터에 설치되어 있습니다.
- 최신 .NET Framework가 설치되어 있습니다.
1단계: Microsoft Visual Studio에서 새 프로젝트를 만듭니다.
이제 새 Visual Studio 프로젝트를 만들어 봅시다.

아래 화면에서 콘솔 애플리케이션 템플릿을 선택하십시오.

프로젝트 이름과 위치를 제공합니다.

가능하면 지원이 포함된 최신 .NET 버전을 선택하고 만들기를 클릭합니다.

2단계: IronWord NuGet 패키지 관리자를 설치합니다.
다음과 같이 Visual Studio에서 NuGet 패키지 관리자를 통해 IronWord NuGet 패키지를 설치하십시오.

또한 아래 명령을 사용하여 CLI에서 직접 설치할 수 있습니다.
dotnet add package IronWord --version 2024.9.1
dotnet add package IronWord --version 2024.9.1
3단계: Word 템플릿 문서를 생성합니다.
이제 Word 문서 생성 과정에서 사용하기 위해 1~2페이지의 Word 템플릿 문서를 생성하십시오.
Dear {Name},
Thanks for purchasing {product}. We are happy to serve you always. Your application dated {Date} has been approved. The product comes with an expiry date of {expiryDate}. Renew the product on or before the expiry date.
Feel free to contact {phone} or {email} for further queries.
Address: {Address}
Thank you,
{Sender}
이제 위의 문서를 Template.docx로 저장하세요.
4단계: Word 문서에 데이터를 삽입하고 새 파일로 저장합니다.
using System;
using System.Collections.Generic;
using IronWord;
class Program
{
static void Main()
{
// Set the license key for IronWord
License.LicenseKey = "your key";
// Define paths for the template and the output file
string templatePath = "Template.docx";
string outputPath = "FilledDocument.docx";
// Create a new instance of the WordDocument class using the template path
WordDocument doc = new WordDocument(templatePath);
// Define a dictionary of placeholders and their replacements
var replacements = new Dictionary<string, string>
{
{ "{Name}", "John Doe" },
{ "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
{ "{Address}", "123 Iron Street, Iron Software" },
{ "{product}", "IronWord" },
{ "{Sender}", "IronSoftware" },
{ "{phone}", "+123 456789" },
{ "{email}", "sale@ironsoftware.com" },
{ "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
};
// Replace placeholders in the document with actual data
foreach (var replacement in replacements)
{
doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
}
// Save the filled document
doc.Save(outputPath);
// Notify the user that the document has been saved successfully
Console.WriteLine("Document filled and saved successfully.");
}
}
using System;
using System.Collections.Generic;
using IronWord;
class Program
{
static void Main()
{
// Set the license key for IronWord
License.LicenseKey = "your key";
// Define paths for the template and the output file
string templatePath = "Template.docx";
string outputPath = "FilledDocument.docx";
// Create a new instance of the WordDocument class using the template path
WordDocument doc = new WordDocument(templatePath);
// Define a dictionary of placeholders and their replacements
var replacements = new Dictionary<string, string>
{
{ "{Name}", "John Doe" },
{ "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
{ "{Address}", "123 Iron Street, Iron Software" },
{ "{product}", "IronWord" },
{ "{Sender}", "IronSoftware" },
{ "{phone}", "+123 456789" },
{ "{email}", "sale@ironsoftware.com" },
{ "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
};
// Replace placeholders in the document with actual data
foreach (var replacement in replacements)
{
doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
}
// Save the filled document
doc.Save(outputPath);
// Notify the user that the document has been saved successfully
Console.WriteLine("Document filled and saved successfully.");
}
}
Imports System
Imports System.Collections.Generic
Imports IronWord
Friend Class Program
Shared Sub Main()
' Set the license key for IronWord
License.LicenseKey = "your key"
' Define paths for the template and the output file
Dim templatePath As String = "Template.docx"
Dim outputPath As String = "FilledDocument.docx"
' Create a new instance of the WordDocument class using the template path
Dim doc As New WordDocument(templatePath)
' Define a dictionary of placeholders and their replacements
Dim replacements = New Dictionary(Of String, String) From {
{"{Name}", "John Doe"},
{"{Date}", DateTime.Now.ToString("MMMM d, yyyy")},
{"{Address}", "123 Iron Street, Iron Software"},
{"{product}", "IronWord"},
{"{Sender}", "IronSoftware"},
{"{phone}", "+123 456789"},
{"{email}", "sale@ironsoftware.com"},
{"{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy")}
}
' Replace placeholders in the document with actual data
For Each replacement In replacements
doc.Texts.ForEach(Function(x) x.Replace(replacement.Key, replacement.Value))
Next replacement
' Save the filled document
doc.Save(outputPath)
' Notify the user that the document has been saved successfully
Console.WriteLine("Document filled and saved successfully.")
End Sub
End Class
설명
제공된 코드는 IronWord 라이브러리를 사용하여 Word 문서 템플릿에 특정 데이터를 채우는 방법을 보여줍니다. 다음은 간결한 설명입니다:
- 라이선스 설정: 코드는 IronWord의 기능을 활성화하기 위해 라이선스 키 설정으로 시작합니다.
- 파일 경로: Word 템플릿 (
Template.docx)과 출력 파일 (FilledDocument.docx)의 경로를 지정합니다. - 문서 인스턴스 생성: 템플릿 경로 참조를 사용하여
WordDocument의 인스턴스를 생성합니다. - 대체 정의: 키는 템플릿의 자리 표시자를 나타내고 값은 삽입할 데이터를 나타내는 사전을 생성합니다.
- 자리 표시자 대체: 사전을 반복하면서 문서의 각 자리 표시자를 해당 데이터로 교체합니다.
- 문서 저장: 마지막으로 업데이트된 문서를 지정된 출력 경로에 저장합니다.
- 완료 메시지: 문서가 성공적으로 채워지고 저장되었음을 확인하는 메시지가 출력됩니다.
산출

5단계: 생성된 Word 문서에 텍스트 효과 추가.
IronWord는 다음 표에 설명된 다양한 텍스트 효과를 추가할 수 있습니다.
다음 예제에서는 "IronSoftware"라는 단어에 텍스트 효과를 추가합니다.
using System;
using System.Collections.Generic;
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
// Set the license key for IronWord
License.LicenseKey = "your key";
// Define paths for the template and the output file
string templatePath = "Template.docx";
string outputPath = "glowEffect.docx";
// Create a new instance of the WordDocument class
WordDocument doc = new WordDocument(templatePath);
// Define a dictionary of placeholders and their replacements
var replacements = new Dictionary<string, string>
{
{ "{Name}", "John Doe" },
{ "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
{ "{Address}", "123 Iron Street, Iron Software" },
{ "{product}", "IronWord" },
{ "{Sender}", "Sale," },
{ "{phone}", "+123 456789" },
{ "{email}", "sale@ironsoftware.com" },
{ "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
};
// Replace placeholders in the document with actual data
foreach (var replacement in replacements)
{
doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
}
// Create and configure text style methods with a glow effect
TextStyle textStyle = new TextStyle
{
TextEffect = new TextEffect()
{
GlowEffect = new Glow()
{
GlowColor = IronWord.Models.Color.Aqua,
GlowRadius = 10,
},
}
};
// Add styled text to the document
doc.AddText(" IronSoftware").Style = textStyle;
// Save the document with the glow effect
doc.SaveAs(outputPath);
// Notify the user that the document has been saved successfully
Console.WriteLine("Styled document saved successfully.");
}
}
using System;
using System.Collections.Generic;
using IronWord;
using IronWord.Models;
class Program
{
static void Main()
{
// Set the license key for IronWord
License.LicenseKey = "your key";
// Define paths for the template and the output file
string templatePath = "Template.docx";
string outputPath = "glowEffect.docx";
// Create a new instance of the WordDocument class
WordDocument doc = new WordDocument(templatePath);
// Define a dictionary of placeholders and their replacements
var replacements = new Dictionary<string, string>
{
{ "{Name}", "John Doe" },
{ "{Date}", DateTime.Now.ToString("MMMM d, yyyy") },
{ "{Address}", "123 Iron Street, Iron Software" },
{ "{product}", "IronWord" },
{ "{Sender}", "Sale," },
{ "{phone}", "+123 456789" },
{ "{email}", "sale@ironsoftware.com" },
{ "{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy") },
};
// Replace placeholders in the document with actual data
foreach (var replacement in replacements)
{
doc.Texts.ForEach(x => x.Replace(replacement.Key, replacement.Value));
}
// Create and configure text style methods with a glow effect
TextStyle textStyle = new TextStyle
{
TextEffect = new TextEffect()
{
GlowEffect = new Glow()
{
GlowColor = IronWord.Models.Color.Aqua,
GlowRadius = 10,
},
}
};
// Add styled text to the document
doc.AddText(" IronSoftware").Style = textStyle;
// Save the document with the glow effect
doc.SaveAs(outputPath);
// Notify the user that the document has been saved successfully
Console.WriteLine("Styled document saved successfully.");
}
}
Imports System
Imports System.Collections.Generic
Imports IronWord
Imports IronWord.Models
Friend Class Program
Shared Sub Main()
' Set the license key for IronWord
License.LicenseKey = "your key"
' Define paths for the template and the output file
Dim templatePath As String = "Template.docx"
Dim outputPath As String = "glowEffect.docx"
' Create a new instance of the WordDocument class
Dim doc As New WordDocument(templatePath)
' Define a dictionary of placeholders and their replacements
Dim replacements = New Dictionary(Of String, String) From {
{"{Name}", "John Doe"},
{"{Date}", DateTime.Now.ToString("MMMM d, yyyy")},
{"{Address}", "123 Iron Street, Iron Software"},
{"{product}", "IronWord"},
{"{Sender}", "Sale,"},
{"{phone}", "+123 456789"},
{"{email}", "sale@ironsoftware.com"},
{"{expiryDate}", DateTime.Now.AddYears(1).ToString("MMMM d, yyyy")}
}
' Replace placeholders in the document with actual data
For Each replacement In replacements
doc.Texts.ForEach(Function(x) x.Replace(replacement.Key, replacement.Value))
Next replacement
' Create and configure text style methods with a glow effect
Dim textStyle As New TextStyle With {
.TextEffect = New TextEffect() With {
.GlowEffect = New Glow() With {
.GlowColor = IronWord.Models.Color.Aqua,
.GlowRadius = 10
}
}
}
' Add styled text to the document
doc.AddText(" IronSoftware").Style = textStyle
' Save the document with the glow effect
doc.SaveAs(outputPath)
' Notify the user that the document has been saved successfully
Console.WriteLine("Styled document saved successfully.")
End Sub
End Class
설명
수정된 코드는 IronWord 라이브러리를 사용하여 Word 문서 템플릿을 작성, 텍스트 스타일 적용 및 수정된 문서 저장을 보여줍니다. 간결한 설명은 다음과 같습니다:
- 라이선스 설정: IronWord 라이선스 키를 설정하여 기능을 활성화합니다.
- 파일 경로: 템플릿 (
Template.docx)과 출력 파일 (glowEffect.docx)의 경로를 지정합니다. - 문서 인스턴스 생성: 제공된 템플릿 경로를 사용하여
WordDocument인스턴스를 초기화합니다. - 대체 정의: 자리 표시자와 대응하는 대체 값을 가진 딕셔너리를 생성합니다.
- 자리 표시자 교체: 딕셔너리를 순회하면서 문서의 자리 표시자를 실제 데이터로 교체합니다.
- 텍스트 스타일 구성: 컬러와 반경을 지정하여 글로우 효과가 있는 텍스트 스타일을 정의합니다.
- 스타일이 적용된 텍스트 추가: 구성된 스타일로 문서에 텍스트를 추가합니다.
- 문서 저장: 적용된 텍스트 스타일을 반영하여 업데이트된 문서를 새 이름 (
glowEffect.docx)으로 저장합니다. - 콘솔 출력: 스타일이 적용된 문서가 저장되었음을 확인하는 메시지를 출력합니다.
산출

IronWord 라이선싱
IronWord. 데이터 입력 후, 제공된 이메일 ID로 라이선스가 전달됩니다. 이 라이선스는 아래와 같이 IronWord 라이브러리를 사용하기 전에 코드의 시작 부분에 배치해야 합니다.
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here"
결론
IronWord는 템플릿을 사용하여 Word 문서를 생성하는 데 여러 이점을 제공합니다. 개발자가 프로그래밍 방식으로 특정 데이터를 사용하여 템플릿을 채울 수 있도록 하여 수동 입력이 필요하지 않게 하여 문서 생성 자동화를 간소화합니다. 인적 오류의 위험을 최소화함으로써 효율성과 정확성을 높입니다. 또한, IronWord는 각 생성된 파일이 동일한 형식과 구조를 준수하도록 하여 문서의 일관성을 유지하는 데 도움을 줍니다. 반복적인 작업을 자동화하여 시간과 자원을 절약하며, 대량의 문서를 신속하게 생성하는 데 이상적입니다. IronWord는 빈번하거나 복잡한 문서 생성을 요구하는 시나리오의 생산성을 향상시키고 워크플로우를 간소화합니다.
이 기사에 설명된 절차를 따르고 IronWord를 활용하여 문서 생성 요구 사항을 효율적으로 관리하고 워크플로우를 간소화할 수 있습니다.
자주 묻는 질문
C#을 사용하여 Word 문서 템플릿을 채우는 방법은 무엇인가요?
IronWord 활용하면 C#으로 Word 문서 템플릿을 채울 수 있습니다. 먼저 Visual Studio에서 프로젝트를 설정하고 NuGet 통해 IronWord 패키지를 설치합니다. Word 템플릿을 만들고 IronWord 사용하여 데이터를 삽입한 다음, 채워진 템플릿을 새 문서로 저장합니다.
Word 템플릿 자동화를 위해 .NET 라이브러리를 사용하면 어떤 이점이 있습니까?
IronWord 와 같은 .NET 라이브러리를 사용하여 Word 템플릿을 자동화하면 수동 입력을 줄이고 오류를 최소화하며 문서 작성의 일관성을 보장할 수 있습니다. 이를 통해 청구서 발행, 송장 발행, 서신 작성과 같은 작업을 효율적으로 처리할 수 있습니다.
워드 템플릿을 프로그램으로 채울 때 텍스트 효과를 추가할 수 있나요?
네, IronWord 사용하면 Word 문서에서 템플릿을 프로그래밍 방식으로 채울 때 텍스트에 빛 효과나 그림자 효과와 같은 텍스트 효과를 추가할 수 있습니다.
Visual Studio 프로젝트에 IronWord 설정하는 데에는 어떤 단계가 포함되나요?
Visual Studio 프로젝트에서 IronWord 설정하려면 먼저 IronWord NuGet 패키지를 설치하고 Word 템플릿을 만든 다음 IronWord의 메서드를 사용하여 문서를 프로그래밍 방식으로 채우고 저장하면 됩니다.
IronWord 문서 생성의 일관성을 어떻게 보장합니까?
IronWord 개발자가 여러 문서에서 동일한 형식과 레이아웃을 유지하는 Word 템플릿을 사용할 수 있도록 하여 일관성을 보장하고 인적 오류의 위험을 줄입니다.
워드 문서 자동 생성의 실제적인 활용 사례는 무엇일까요?
IronWord 를 이용한 워드 문서 자동 생성은 보고서 작성, 송장 발행, 계약 관리, 개인 맞춤형 편지 작성 등 다양한 시나리오에 적용할 수 있습니다.
IronWord 사용하여 Microsoft Word의 여러 버전을 처리할 수 있습니까?
네, IronWord 다양한 버전의 Microsoft Word와 호환되므로 서로 다른 환경에서 문서를 원활하게 처리할 수 있습니다.
IronWord 사용하여 Word 문서를 관리하려면 무엇이 필요합니까?
IronWord 사용하려면 Visual Studio와 최신 .NET Framework 설치되어 있는지 확인하십시오. 그런 다음 NuGet 패키지 관리자를 통해 IronWord 프로젝트에 추가하십시오.



