C# 高效生成 Word 表格:复杂表格创建实战指南

0 阅读3分钟

ChatGPT Image Nov 26, 2025, 06_03_44 PM.png

在现代办公自动化中,Word 文档依然是信息呈现和数据输出的重要载体。无论是月度报表、客户合同,还是内部汇总文档,表格都是不可或缺的元素。手动创建表格不仅效率低,而且容易出错。借助 C# 编程,我们可以轻松实现 Word 表格的自动生成、格式化以及复杂操作。

本文将系统介绍如何使用 Free Spire.Doc for .NET 处理 Word 表格,包括表格样式设置、动态添加删除行列、以及单元格内嵌套表格等操作。通过这些技巧,您可以快速生成符合业务需求的高质量文档。

安装 Free Spire.Doc for .NET:Install-Package FreeSpire.Doc


1. C# 操作 Word 表格的对象模型

在操作表格之前,需要理解 Word 文档的对象结构:

  • Document:文档整体对象
  • Section:文档的分节,每个 Section 可包含多个段落或表格
  • Table:表格对象
  • TableRow:表格行
  • TableCell:表格单元格
  • Paragraph:单元格或正文中的段落
  • TextRange:段落中实际文本
  • ParagraphStyle:段落样式,统一管理字体、字号、对齐方式等

掌握这些对象的层级关系,可以更灵活地控制表格内容与样式。


2. 创建并格式化表格

在很多业务场景中,表格不仅需要展示数据,还要美观、清晰。下面示例展示如何创建一个销售数据表,设置列宽、行高、背景色和字体样式。

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

public class WordTableDemo
{
    public static void CreateFormattedTable(string filePath)
    {
        Document doc = new Document();
        Section sec = doc.AddSection();

        // 添加标题
        Paragraph title = sec.AddParagraph();
        TextRange tr = title.AppendText("2025年度产品销售统计");
        tr.CharacterFormat.FontName = "Yu Gothic UI";
        tr.CharacterFormat.FontSize = 18;
        tr.CharacterFormat.Bold = true;
        title.Format.HorizontalAlignment = HorizontalAlignment.Center;

        sec.AddParagraph().AppendText("\n"); // 间距

        // 创建表格
        Table table = sec.AddTable();
        table.ResetCells(5, 4); // 5行4列
        table.TableFormat.Borders.BorderType = BorderStyle.Single;
        table.TableFormat.Borders.LineWidth = 1f;
        table.TableFormat.Borders.Color = Color.DarkGray;

        // 设置列宽
        int[] colWidths = { 80, 200, 100, 120 };
        foreach (TableRow row in table.Rows)
        {
            for (int i = 0; i < colWidths.Length; i++)
                row.Cells[i].SetCellWidth(colWidths[i], CellWidthType.Point);
        }

        // 表头样式
        ParagraphStyle headerStyle = doc.AddParagraphStyle("headerStyle");
        headerStyle.CharacterFormat.Bold = true;
        headerStyle.CharacterFormat.FontName = "Yu Gothic UI";
        headerStyle.CharacterFormat.FontSize = 13;
        headerStyle.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;

        string[] headers = { "产品编号", "产品名称", "销售数量", "销售金额" };
        for (int i = 0; i < headers.Length; i++)
        {
            TableCell cell = table.Rows[0].Cells[i];
            cell.CellFormat.BackColor = Color.LightSteelBlue;
            cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
            Paragraph p = cell.AddParagraph();
            p.AppendText(headers[i]);
            p.ApplyStyle(headerStyle.Name);
        }

        // 数据样式
        ParagraphStyle dataStyle = doc.AddParagraphStyle("dataStyle");
        dataStyle.CharacterFormat.FontName = "Yu Gothic UI";
        dataStyle.CharacterFormat.FontSize = 12;
        dataStyle.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;

        string[,] data = {
            { "A101", "超薄笔记本", "120", "180000" },
            { "B202", "智能手机", "450", "540000" },
            { "C303", "无线耳机", "300", "90000" },
            { "D404", "智能手表", "200", "80000" }
        };

        for (int r = 0; r < data.GetLength(0); r++)
        {
            for (int c = 0; c < data.GetLength(1); c++)
            {
                TableCell cell = table.Rows[r + 1].Cells[c];
                Paragraph p = cell.AddParagraph();
                p.AppendText(data[r, c]);
                p.ApplyStyle(dataStyle.Name);
                cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
            }
        }

        doc.SaveToFile(filePath, FileFormat.Docx);
        Console.WriteLine($"文档已生成:{filePath}");
    }
}

此示例展示了如何创建格式化表格、设置列宽、行高和背景色,同时应用统一字体样式。

生成结果预览

2025-11-26_175817.png


3. 动态添加与删除行列

实际业务中,表格行列数量可能不固定,需要根据数据动态调整:

// 添加新行
public static void AddRow(Table table, string[] rowData)
{
    TableRow newRow = table.AddRow();
    newRow.Height = 22;
    newRow.HeightType = TableRowHeightType.Auto;

    for (int i = 0; i < rowData.Length; i++)
    {
        TableCell cell = newRow.Cells[i];
        Paragraph p = cell.AddParagraph();
        p.AppendText(rowData[i]);
        p.Format.HorizontalAlignment = HorizontalAlignment.Center;
        cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
    }
}

// 删除行
public static void RemoveRow(Table table, int rowIndex)
{
    if (rowIndex >= 0 && rowIndex < table.Rows.Count)
        table.Rows.RemoveAt(rowIndex);
}

// 添加列
public static void AddColumn(Table table, int colIndex, string[] colData)
{
    for (int r = 0; r < table.Rows.Count; r++)
    {
        TableCell newCell = new TableCell(table.Document);
        table.Rows[r].Cells.Insert(colIndex, newCell);
        Paragraph p = newCell.AddParagraph();
        if (r < colData.Length) p.AppendText(colData[r]);
        p.Format.HorizontalAlignment = HorizontalAlignment.Center;
        newCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
    }
}

// 删除列
public static void RemoveColumn(Table table, int colIndex)
{
    for (int r = 0; r < table.Rows.Count; r++)
    {
        if (colIndex >= 0 && colIndex < table.Rows[r].Cells.Count)
            table.Rows[r].Cells.RemoveAt(colIndex);
    }
}

使用这些方法,表格可以根据实际数据动态扩展或缩减,非常适合报表和数据汇总场景。


4. 单元格内嵌套表格

在合同条款、问卷或复杂布局中,可能需要在一个单元格内部嵌入表格:

using Spire.Doc;
using Spire.Doc.Documents;


public class WordTableDemo
{
    public static void InsertNestedTable(string filePath)
    {
        Document doc = new Document();
        Section sec = doc.AddSection();

        sec.AddParagraph().AppendText("嵌套表格示例").CharacterFormat.FontSize = 16;
        sec.AddParagraph().AppendText("\n");

        Table outer = sec.AddTable();
        outer.ResetCells(2, 2);
        outer.TableFormat.Borders.BorderType = BorderStyle.Single;

        outer.Rows[0].Cells[0].AddParagraph().AppendText("外表格 (0,0)");

        TableCell nestedCell = outer.Rows[0].Cells[1];
        nestedCell.AddParagraph().AppendText("内部表格如下:");

        Table inner = nestedCell.AddTable();
        inner.ResetCells(3, 2);
        inner.TableFormat.Borders.BorderType = BorderStyle.Dot;

        string[,] innerData = {
        { "编号", "名称" },
        { "001", "笔记本" },
        { "002", "手机" }
    };

        for (int r = 0; r < innerData.GetLength(0); r++)
        {
            for (int c = 0; c < innerData.GetLength(1); c++)
            {
                TableCell cell = inner.Rows[r].Cells[c];
                cell.AddParagraph().AppendText(innerData[r, c]);
                cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                cell.Paragraphs[0].Format.HorizontalAlignment = HorizontalAlignment.Center;
            }
        }

        outer.Rows[1].Cells[0].AddParagraph().AppendText("外表格 (1,0)");
        outer.Rows[1].Cells[1].AddParagraph().AppendText("外表格 (1,1)");

        doc.SaveToFile(filePath, FileFormat.Docx);
        Console.WriteLine($"嵌套表格文档已生成:{filePath}");
    }

    static void Main(string[] args)
    {
        InsertNestedTable("NestedTable.docx");
    }
}

嵌套表格能够在一个单元格内呈现多层信息,例如条款编号+说明内容,或分区统计数据。

生成结果预览

2025-11-26_180003.png


5. 总结

本文展示了使用 C# 与 Free Spire.Doc for .NET 操作 Word 表格的多种技巧:

  1. 创建格式化表格,并统一设置列宽、行高、背景色和字体样式
  2. 动态添加或删除行列,适配数据量变化
  3. 在单元格内嵌套表格,实现更灵活的文档布局

通过这些方法,开发者可以轻松实现高质量的 Word 报表、合同或汇总文档。结合 Free Spire.Doc 的其他 API,还可扩展图片插入、分页控制和 PDF 导出等功能,使文档生成更智能化。