Batch Generate Word Documents in C#: One per Excel Row

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

Batch Generate Word Documents from Excel

When product names, prices, specifications, and photos already live in Excel, building a separate Word document for each product means repeating the same manual steps row by row. A reusable Word template combined with a C# console app lets you batch generate Word documents from that catalog while keeping the layout consistent across every product.

This tutorial shows how to batch generate Word documents from Excel in C# using Spire.XLS and Spire.Doc. The .NET 10 example fills a reusable Word template with each product’s details and photo, then saves one DOCX file per product using its SKU as the filename.

Prepare the Excel Data and Word Template

In ProductCatalog.xlsx, the Products worksheet has headers in row 1 and one product per row starting at row 2. Column A contains the SKU, column D stores the price as a number, and column G contains multiple lines of technical specifications in a single cell. Column I contains floating PNG images with transparent backgrounds. The upper-left corner of each picture is anchored in the row it belongs to, at I2, I3, or I4.

Excel Data

ProductSpecificationTemplate.docx defines the layout of the finished sheet. It contains nine placeholders:

Excel column Field Word placeholder
A SKU {{sku}}
B ProductName {{product_name}}
C Category {{category}}
D UnitPrice {{unit_price}}
E WarrantyMonths {{warranty_months}}
F Description {{description}}
G Specifications {{specifications}}
H PackageContents {{package_contents}}
I Photo {{photo}}

Keep {{specifications}} and {{photo}} in their own paragraphs. The code uses the first paragraph to write the specification lines and the second to place the image in the template’s right-hand cell. The template already supplies the word “months” after the warranty value.

Word Template File

How the Excel-to-Word Workflow Works

Take HUB-007, the first product. The program loads a fresh copy of the template, takes the product name from B2, and replaces {{product_name}} with that text. For the photo, it finds the picture anchored at I2, locates {{photo}} in Word, and inserts an image at the placeholder’s position before removing the placeholder text. It then saves the filled document as HUB-007.docx and repeats the process for the next row.

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

Cell(2) reads column B of the current row. FillPhoto receives the same row number and column 9, so the picture and the text come from the same product record.

Set Up the .NET 10 Console Project

Create a console project targeting net10.0, then install the three NuGet packages used in this example. Spire.XLS reads the Excel data and embedded product images, Spire.Doc fills the Word template and saves the DOCX files, and SkiaSharp encodes the product images as PNG to preserve transparency.

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

Replace the contents of Program.cs with the complete example below. Place ProductCatalog.xlsx and ProductSpecificationTemplate.docx in the directory where you run dotnet run, or set their absolute paths at the top of the code. The program creates an Output directory for the generated Word documents.

Step 1. Read Each Product Row from Excel

Load the workbook once and select the Products worksheet by name. In the loop, start at row 2 to skip the headers. The local Cell function reads trimmed text from the current row. If the SKU is blank, the program skips the row. The complete example also checks that the SKU is suitable for use as a filename.

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.
}

For UnitPrice, read the numeric value with NumberValue and format it explicitly as US currency. The en-US culture and C2 format turn the numeric value 49.9 into $49.90 consistently across machines with different regional settings.

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

Step 2. Fill the Word Template and Preserve Line Breaks

Load the template inside the loop so each product starts with all placeholders available. Use Document.Replace for single-value fields. The calls use case-sensitive matching and leave whole-word matching disabled for the brace-delimited placeholders.

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);

The Specifications cell is handled separately. FillSpecifications finds its placeholder paragraph, removes the token, normalizes the incoming line endings, and writes each line with a Word line break between entries. This keeps the technical details on separate lines within the same paragraph.

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]);
    }
}

Step 3. Insert the Product Photo at Its Placeholder

FillPhoto looks through sheet.Pictures for an image whose TopRow and LeftColumn match the current row and the photo column. SkiaSharp encodes the bitmap as PNG to retain its transparent background. The code loads that PNG into a DocPicture and applies the same scale to its width and height to fit within 190 × 120 points.

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);
}

The method inserts the picture at the placeholder’s index in the paragraph. It then removes {{photo}}, even if no matching picture was found. All three sample products have matching images.

Step 4. Save One Word Document per SKU

The loop builds the output filename from the SKU and skips the row if that file already exists. After filling the template, it serializes the DOCX to a memory stream and writes it to disk with FileMode.CreateNew, which prevents an existing file from being overwritten.

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

Run the project with dotnet run. With an empty output directory, the sample catalog produces HUB-007.docx, STAND-014.docx, and MOUSE-021.docx.

Generated Documents

Complete C# Example

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();
}

Conclusion

You can batch generate Word documents from Excel in C# by pairing a worksheet with a reusable Word template. Each row supplies the data and photo for one document, while the template controls how the product details are presented.

The same approach works for employee letters, equipment inspection reports, and certificates. Match the Excel columns to the placeholders in your Word template, then use each row to generate a separate document. For example, an employee roster can supply names, job titles, and start dates for a batch of onboarding letters.

See Also