C#에서 Word 문서 일괄 생성: Excel 행마다 하나씩

2026-11-27 09:37:53 Jack Du
AI Summarize:
ChatGPT
ChatGPT ✓
Claude ✓
Grok ✓
Perplexity ✓
Quick
Quick
Concise overview
Highlights
Key takeaways
Detailed
Structured explanation
Brief
One sentence summary
Summarize |

Excel에서 Word 문서 일괄 생성

제품 이름, 가격, 사양 및 사진이 이미 Excel에 있는 경우 각 제품에 대해 별도의 Word 문서를 만들려면 동일한 수동 단계를 행마다 반복해야 합니다. 재사용 가능한 Word 템플릿과 C# 콘솔 앱을 결합하면 모든 제품에서 레이아웃을 일관되게 유지하면서 해당 카탈로그에서 Word 문서를 일괄 생성할 수 있습니다.

이 자습서에서는 Spire.XLS와 Spire.Doc을 사용하여 C#에서 Excel로부터 Word 문서를 일괄 생성하는 방법을 보여 줍니다. .NET 10 예제는 재사용 가능한 Word 템플릿에 각 제품의 세부 정보와 사진을 채운 다음, SKU를 파일 이름으로 사용하여 제품당 하나의 DOCX 파일을 저장합니다.

Excel 데이터와 Word 템플릿 준비

ProductCatalog.xlsx의 Products 워크시트에는 1행에 헤더가 있고 2행부터 제품이 한 행에 하나씩 있습니다. A열에는 SKU가 포함되어 있고, D열에는 가격이 숫자로 저장되며, G열에는 한 셀에 여러 줄의 기술 사양이 포함되어 있습니다. I열에는 투명 배경의 떠 있는 PNG 이미지가 포함되어 있습니다. 각 사진의 왼쪽 위 모서리는 해당 사진이 속한 행의 I2, I3 또는 I4에 고정되어 있습니다.

Excel 데이터

ProductSpecificationTemplate.docx는 완성된 시트의 레이아웃을 정의합니다. 아홉 개의 자리 표시자가 포함되어 있습니다:

Excel 열 필드 Word 자리 표시자
A SKU {{sku}}
B 제품명 {{product_name}}
C 카테고리 {{category}}
D 단가 {{unit_price}}
E 보증 개월 {{warranty_months}}
F 설명 {{description}}
G 사양 {{specifications}}
H 패키지 내용 {{package_contents}}
I 사진 {{photo}}

{{specifications}}와 {{photo}}는 각각 별도의 단락에 유지하세요. 코드는 첫 번째 단락을 사용해 사양 줄을 쓰고, 두 번째 단락을 사용해 템플릿의 오른쪽 셀에 이미지를 배치합니다. 템플릿에는 이미 보증 값 뒤에 “months”라는 단어가 제공되어 있습니다.

Word 템플릿 파일

Excel에서 Word로의 워크플로 작동 방식

첫 번째 제품인 HUB-007을 예로 들어 보겠습니다. 프로그램은 템플릿의 새 복사본을 로드하고, B2에서 제품 이름을 가져와 {{product_name}}을 해당 텍스트로 바꿉니다. 사진의 경우 I2에 고정된 그림을 찾고, Word에서 {{photo}}를 찾은 다음 자리 표시자 위치에 이미지를 삽입한 후 자리 표시자 텍스트를 제거합니다. 그런 다음 채워진 문서를 HUB-007.docx로 저장하고 다음 행에 대해 프로세스를 반복합니다.

doc.Replace("{{product_name}}", Cell(2), true, false);
FillPhoto(doc, sheet, row, photoColumn);

Cell(2)는 현재 행의 B열을 읽습니다. FillPhoto는 동일한 행 번호와 9열을 받으므로 사진과 텍스트가 동일한 제품 레코드에서 가져옵니다.

.NET 10 콘솔 프로젝트 설정

net10.0을 대상으로 하는 콘솔 프로젝트를 만든 다음, 이 예제에서 사용하는 세 가지 NuGet 패키지를 설치합니다. Spire.XLS는 Excel 데이터와 포함된 제품 이미지를 읽고, Spire.Doc은 Word 템플릿을 채우고 DOCX 파일을 저장하며, SkiaSharp는 투명도를 유지하기 위해 제품 이미지를 PNG로 인코딩합니다.

dotnet new console --framework net10.0 -o BatchWordFromExcel
cd BatchWordFromExcel
dotnet add package Spire.XLS
dotnet add package Spire.Doc
dotnet add package SkiaSharp

Program.cs의 내용을 아래 전체 예제로 바꾸세요. ProductCatalog.xlsx와 ProductSpecificationTemplate.docx를 dotnet run을 실행하는 디렉터리에 두거나 코드 상단에 절대 경로를 설정하세요. 프로그램은 생성된 Word 문서를 위해 Output 디렉터리를 만듭니다.

1단계. Excel에서 각 제품 행 읽기

통합 문서를 한 번 로드하고 이름으로 Products 워크시트를 선택합니다. 루프에서는 헤더를 건너뛰기 위해 2행부터 시작합니다. 로컬 Cell 함수는 현재 행에서 공백을 제거한 텍스트를 읽습니다. SKU가 비어 있으면 프로그램은 해당 행을 건너뜁니다. 전체 예제에서는 SKU가 파일 이름으로 사용하기에 적합한지도 확인합니다.

using var workbook = new Workbook();
workbook.LoadFromFile(excelPath);
Worksheet sheet = workbook.Worksheets["Products"];
var usCulture = CultureInfo.GetCultureInfo("en-US");

for (int row = 2; row <= sheet.LastRow; row++)
{
    string Cell(int column) => sheet.Range[row, column].Value?.Trim() ?? "";

    string sku = Cell(1);
    if (sku.Length == 0)
        continue;

    // Fill and save the document for this row.
}

UnitPrice의 경우 NumberValue로 숫자 값을 읽고 미국 통화 형식으로 명시적으로 서식을 지정합니다. en-US 문화권과 C2 형식은 숫자 값 49.9를 서로 다른 지역 설정을 가진 컴퓨터에서도 일관되게 $49.90으로 변환합니다.

string price = sheet.Range[row, 4].NumberValue.ToString("C2", usCulture);

2단계. Word 템플릿 채우기 및 줄 바꿈 유지

각 제품이 모든 자리 표시자를 사용할 수 있는 상태로 시작하도록 루프 안에서 템플릿을 로드합니다. 단일 값 필드에는 Document.Replace를 사용합니다. 호출은 대/소문자 구분 일치를 사용하며 중괄호로 구분된 자리 표시자에 대해서는 전체 단어 일치를 비활성화합니다.

using var doc = new Document();
doc.LoadFromFile(templatePath);

string price = sheet.Range[row, 4].NumberValue.ToString("C2", usCulture);

doc.Replace("{{sku}}", sku, true, false);
doc.Replace("{{product_name}}", Cell(2), true, false);
doc.Replace("{{category}}", Cell(3), true, false);
doc.Replace("{{unit_price}}", price, true, false);
doc.Replace("{{warranty_months}}", Cell(5), true, false);
doc.Replace("{{description}}", Cell(6), true, false);
doc.Replace("{{package_contents}}", Cell(8), true, false);

Specifications 셀은 별도로 처리합니다. FillSpecifications는 해당 자리 표시자 단락을 찾고, 토큰을 제거하고, 들어오는 줄 바꿈을 정규화한 뒤 각 항목 사이에 Word 줄 바꿈을 넣어 각 줄을 씁니다. 이렇게 하면 기술 세부 정보가 동일한 단락 내에서 별도 줄에 유지됩니다.

static void FillSpecifications(Document doc, string specifications)
{
    // The template places this placeholder in a paragraph of its own.
    TextRange placeholder = FindToken(doc, "{{specifications}}");
    Paragraph paragraph = placeholder.OwnerParagraph;
    paragraph.ChildObjects.Remove(placeholder);

    string[] lines = specifications.ReplaceLineEndings("\n").Split('\n');
    for (int i = 0; i < lines.Length; i++)
    {
        if (i > 0)
            paragraph.AppendBreak(BreakType.LineBreak);

        paragraph.AppendText(lines[i]);
    }
}

3단계. 자리 표시자에 제품 사진 삽입

FillPhoto는 sheet.Pictures에서 TopRow와 LeftColumn이 현재 행 및 사진 열과 일치하는 이미지를 찾습니다. SkiaSharp는 비트맵을 PNG로 인코딩하여 투명 배경을 유지합니다. 코드는 해당 PNG를 DocPicture에 로드하고 너비와 높이에 동일한 배율을 적용하여 190 × 120포인트 안에 맞춥니다.

static void FillPhoto(Document doc, Worksheet sheet, int row, int column)
{
    TextRange placeholder = FindToken(doc, "{{photo}}");
    Paragraph paragraph = placeholder.OwnerParagraph;

    foreach (ExcelPicture picture in sheet.Pictures)
    {
        if (picture.TopRow != row || picture.LeftColumn != column)
            continue;

        // PNG encoding retains the bitmap's alpha channel.
        using SKBitmap bitmap = picture.Picture;
        using SKData png = bitmap.Encode(SKEncodedImageFormat.Png, 100);
        using var imageStream = new MemoryStream(png.ToArray());

        var image = new DocPicture(doc);
        image.LoadImage(imageStream);

        // Fit the photo inside the right-hand cell without stretching it.
        const float maxWidth = 190;
        const float maxHeight = 120;
        float width = image.Width;
        float height = image.Height;
        float scale = Math.Min(maxWidth / width, maxHeight / height);
        image.Width = width * scale;
        image.Height = height * scale;
        image.AspectRatioLocked = true;

        int index = paragraph.ChildObjects.IndexOf(placeholder);
        paragraph.ChildObjects.Insert(index, image);
        break;
    }

    // Remove the token even when the row has no matching photo.
    paragraph.ChildObjects.Remove(placeholder);
}

이 메서드는 단락에서 자리 표시자의 인덱스에 그림을 삽입합니다. 그런 다음 일치하는 그림이 발견되지 않더라도 {{photo}}를 제거합니다. 세 가지 샘플 제품 모두 일치하는 이미지가 있습니다.

4단계. SKU별 Word 문서 하나씩 저장

루프는 SKU로 출력 파일 이름을 만들고 해당 파일이 이미 존재하면 행을 건너뜁니다. 템플릿을 채운 후 DOCX를 메모리 스트림으로 직렬화하고 FileMode.CreateNew로 디스크에 기록하여 기존 파일을 덮어쓰지 않습니다.

using var buffer = new MemoryStream();
doc.SaveToStream(buffer, WordFormat.Docx);
buffer.Position = 0;
using var output = new FileStream(outputPath, FileMode.CreateNew);
buffer.CopyTo(output);

dotnet run으로 프로젝트를 실행합니다. 출력 디렉터리가 비어 있으면 샘플 카탈로그는 HUB-007.docx, STAND-014.docx, MOUSE-021.docx를 생성합니다.

생성된 문서

전체 C# 예제

using System.Globalization;
using System.Text.RegularExpressions;
using SkiaSharp;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using WordFormat = Spire.Doc.FileFormat;

// Place both input files in the working directory, or use absolute paths.
const string excelPath = "ProductCatalog.xlsx";
const string templatePath = "ProductSpecificationTemplate.docx";
const string outputDir = "Output";
const int photoColumn = 9;

Directory.CreateDirectory(outputDir);

using var workbook = new Workbook();
workbook.LoadFromFile(excelPath);
Worksheet sheet = workbook.Worksheets["Products"];
var usCulture = CultureInfo.GetCultureInfo("en-US");
int generated = 0;

for (int row = 2; row <= sheet.LastRow; row++)
{
    string Cell(int column) => sheet.Range[row, column].Value?.Trim() ?? "";

    string sku = Cell(1);
    if (sku.Length == 0)
        continue;

    // Accept the catalog's SKU format and reject reserved Windows names.
    if (!Regex.IsMatch(sku, @"\A[A-Za-z0-9_-]+\z") ||
        Regex.IsMatch(sku, @"\A(?:CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])\z",
            RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
    {
        Console.WriteLine($"Skipping row {row}: invalid SKU '{sku}'.");
        continue;
    }

    string outputPath = Path.Combine(outputDir, sku + ".docx");
    if (File.Exists(outputPath))
    {
        Console.WriteLine($"Skipping row {row}: {sku}.docx already exists.");
        continue;
    }

    using var doc = new Document();
    doc.LoadFromFile(templatePath);

    // Read the numeric price and format it consistently as US dollars.
    string price = sheet.Range[row, 4].NumberValue.ToString("C2", usCulture);

    doc.Replace("{{sku}}", sku, true, false);
    doc.Replace("{{product_name}}", Cell(2), true, false);
    doc.Replace("{{category}}", Cell(3), true, false);
    doc.Replace("{{unit_price}}", price, true, false);
    doc.Replace("{{warranty_months}}", Cell(5), true, false);
    doc.Replace("{{description}}", Cell(6), true, false);
    FillSpecifications(doc, Cell(7));
    doc.Replace("{{package_contents}}", Cell(8), true, false);
    FillPhoto(doc, sheet, row, photoColumn);

    // CreateNew also protects against an existing file created after the check.
    using var buffer = new MemoryStream();
    doc.SaveToStream(buffer, WordFormat.Docx);
    buffer.Position = 0;
    using var output = new FileStream(outputPath, FileMode.CreateNew);
    buffer.CopyTo(output);
    generated++;

    Console.WriteLine($"Created {outputPath}");
}

Console.WriteLine($"Generated {generated} Word document(s).");

static void FillSpecifications(Document doc, string specifications)
{
    // The template places this placeholder in a paragraph of its own.
    TextRange placeholder = FindToken(doc, "{{specifications}}");
    Paragraph paragraph = placeholder.OwnerParagraph;
    paragraph.ChildObjects.Remove(placeholder);

    string[] lines = specifications.ReplaceLineEndings("\n").Split('\n');
    for (int i = 0; i < lines.Length; i++)
    {
        if (i > 0)
            paragraph.AppendBreak(BreakType.LineBreak);

        paragraph.AppendText(lines[i]);
    }
}

static void FillPhoto(Document doc, Worksheet sheet, int row, int column)
{
    TextRange placeholder = FindToken(doc, "{{photo}}");
    Paragraph paragraph = placeholder.OwnerParagraph;

    foreach (ExcelPicture picture in sheet.Pictures)
    {
        if (picture.TopRow != row || picture.LeftColumn != column)
            continue;

        // PNG encoding retains the bitmap's alpha channel.
        using SKBitmap bitmap = picture.Picture;
        using SKData png = bitmap.Encode(SKEncodedImageFormat.Png, 100);
        using var imageStream = new MemoryStream(png.ToArray());

        var image = new DocPicture(doc);
        image.LoadImage(imageStream);

        // Fit the photo inside the right-hand cell without stretching it.
        const float maxWidth = 190;
        const float maxHeight = 120;
        float width = image.Width;
        float height = image.Height;
        float scale = Math.Min(maxWidth / width, maxHeight / height);
        image.Width = width * scale;
        image.Height = height * scale;
        image.AspectRatioLocked = true;

        int index = paragraph.ChildObjects.IndexOf(placeholder);
        paragraph.ChildObjects.Insert(index, image);
        break;
    }

    // Remove the token even when the row has no matching photo.
    paragraph.ChildObjects.Remove(placeholder);
}

static TextRange FindToken(Document doc, string token)
{
    TextSelection selection = doc.FindString(token, true, false);
    if (selection == null)
        throw new InvalidDataException($"Template placeholder not found: {token}");

    return selection.GetAsOneRange();
}

결론

Excel의 워크시트를 재사용 가능한 Word 템플릿과 결합하여 C#에서 Excel로부터 Word 문서를 일괄 생성할 수 있습니다. 각 행은 하나의 문서에 대한 데이터와 사진을 제공하며, 템플릿은 제품 세부 정보가 표시되는 방식을 제어합니다.

동일한 접근 방식은 직원 편지, 장비 검사 보고서 및 인증서에도 사용할 수 있습니다. Excel 열을 Word 템플릿의 자리 표시자와 일치시킨 다음 각 행을 사용하여 별도의 문서를 생성하세요. 예를 들어, 직원 명부는 온보딩 편지 묶음에 필요한 이름, 직책 및 시작 날짜를 제공할 수 있습니다.

참고 항목