C#使用OpenXml SDK向Word文档动态添加表格

巷口听风
巷口听风
发布时间:2026-10-14| 5人浏览过
原创

本文介绍了如何使用C#结合OpenXml库在Word文档中插入表格,涵盖了从引入命名空间、配置网格与边框到追加数据的完整实现。

核心逻辑与目标

在Word文档中添加表格并非直接写入文本,而是需要构建符合Office Open XML (OOXML)标准的对象树。主要涉及以下核心对象:

  • WordprocessingDocument:用于打开和读写Word文件。
  • TableGrid:定义表格的列数及宽度分布。
  • Table与TableProperties:控制表格的整体样式(如边框)。
  • TableRow与TableCell:构成表格的具体行与单元格内容。

准备条件

1. 开发环境:Visual Studio 或兼容的 C# IDE。 2. 依赖库:安装 DocumentFormat.OpenXml NuGet 包。 3. 输入源:一个现有的Word文件路径(例如“Test.docx”)以及待填入的数据数组。

真实操作顺序

第1步:初始化文档与网格配置

目的:加载目标Word文件,并根据数据列数创建对应的列宽网格。

关键动作:

  1. 使用 WordprocessingDocument.Open(wordPath, true) 以可写模式打开文件。
  2. 计算数据的最大列数 (maxColumnNum)。
  3. 循环实例化 new TableGrid() 并将其附加到 grid 变量,确保列结构与数据对齐。

第2步:配置表格边框样式

目的:使生成的表格具有视觉上的边界区分。

参数与入口:创建 TableProperties,内部嵌套 TableBorders。

关键参数说明:

  • 类型:BorderValues.Single(单实线)。
  • 大小:Size = 2(对应磅值,数值越大边框越粗)。
  • 应用方向:顶部、底部、左侧、右侧、水平内边距、垂直内边距均需设置。

第3步:构建并插入表头

目的:在表格第一行显示列名。

动作:遍历表头字符串数组,为每个元素创建 TableCell,并在单元格内追加 Paragraph → Run → Text 结构。

第4步:填充数据行

目的:将二维数据数组转换为表格主体。

动作:遍历数据列表 lstData,对每一行重复第3步的操作创建 TableRow,然后将生成的行追加到 table 对象中。

第5步:将表格挂载至文档

目的:保存修改后的文档内容。

动作:调用 doc.MainDocumentPart.Document.Body.Append(new Paragraph(new Run(table)))。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace AddTableToWord
{
  public class Program
  {
    public static void Main(string[] args)
    {
      // 模拟数据源
      List<string[]> lstData = new List<string[]>() 
      { 
        new string[] { "1", "2", "3" }, 
        new string[] { "3", "2", "1" } 
      };
      string[] headerArray = new string[] { "A", "B", "C" };
      
      // 执行添加表格操作
      AddTable("Test.docx", lstData, headerArray);
    }

    /// <summary>
    /// 在Word文件中指定位置添加表格
    /// </summary>
    public static void AddTable(string wordPath, List<string[]> lstData, string[] headerArray)
    {
      using (WordprocessingDocument doc = WordprocessingDocument.Open(wordPath, true))
      {
        TableGrid grid = new TableGrid();
        int maxColumnNum = lstData.Select(x => x.Count()).Max();
        for (int index = 0; index < maxColumnNum; index++)
        {
          grid.Append(new TableGrid());
        }

        // 设置表格边框
        TableProperties tblProp = new TableProperties(
        new TableBorders(
        new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
        new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 }
        )
        );

        Table table = new Table();
        table.Append(tblProp);

        // 添加表头
        TableRow headerRow = new TableRow();
        foreach (string headerStr in headerArray)
        {
          TableCell cell = new TableCell();
          cell.Append(new Paragraph(new Run(new Text(headerStr))));
          headerRow.Append(cell);
        }
        table.Append(headerRow);

        // 添加数据
        foreach (string[] rowArray in lstData)
        {
          TableRow row = new TableRow();
          foreach (string strCell in rowArray)
          {
            TableCell cell = new TableCell();
            cell.Append(new Paragraph(new Run(new Text(strCell))));
            row.Append(cell);
          }
          table.Append(row);
        }

        doc.MainDocumentPart.Document.Body.Append(new Paragraph(new Run(table)));
      }
    }
  }
}

运行上述代码后,Word文档中将出现一个带有完整边框且包含三列数据的表格。

简要总结

以上就是C#采用OpenXml给Word文档添加表格的详细内容,更多关于C#生成Word报表的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。