C#实现高效生成Word复杂表格的实战指南

 更新时间:2025年11月27日 08:20:01   作者:用户835629078051  
在现代办公自动化中,Word 文档依然是信息呈现和数据输出的重要载体,本文将系统介绍如何使用 Free Spire.Doc for .NET 处理 Word 表格,希望对大家有所帮助

在现代办公自动化中,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}");
    }
}

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

生成结果预览

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

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

生成结果预览

5. 总结

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

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

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

到此这篇关于C#实现高效生成Word复杂表格的实战指南的文章就介绍到这了,更多相关C#生成Word复杂表格内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Unity调用打印机打印图片

    Unity调用打印机打印图片

    这篇文章主要为大家详细介绍了Unity通过调用打印机打印图片的代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-10-10
  • C#读写INI文件的最简方法

    C#读写INI文件的最简方法

    INI文件,全称为Initialization File(初始化文件),是一种传统的文本型配置文件格式,广泛应用于Windows操作系统及早期应用程序中,本文将聚焦于C#语言环境下,介绍如何以最简化的方式实现INI文件的读写操,需要的朋友可以参考下
    2025-01-01
  • opencvsharp瑕疵检测的实现示例

    opencvsharp瑕疵检测的实现示例

    本文主要介绍了opencvsharp瑕疵检测的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-05-05
  • winform壁纸工具为图片添加当前月的日历信息

    winform壁纸工具为图片添加当前月的日历信息

    使用用winform做了一个设置壁纸小工具,为图片添加当月的日历并设为壁纸,可以手动/定时设置壁纸,最主要的特点是在图片上生成当前月的日历信息,感兴趣的你可以参考下
    2013-03-03
  • C#使用Stack<T>进行堆栈设计的实现

    C#使用Stack<T>进行堆栈设计的实现

    堆栈代表了一个后进先出的对象集合,当您需要对各项进行后进先出的访问时,则使用堆栈,本文主要介绍了C#使用Stack<T>类进行堆栈设计的实现,文中通过示例代码介绍的非常详细,感兴趣的可以了解一下
    2024-03-03
  • C# 执行bat批处理文件的小例子

    C# 执行bat批处理文件的小例子

    这篇文章介绍了C# 执行bat批处理文件的小例子,有需要的朋友可以参考一下
    2013-10-10
  • C# 异步多线程入门到精通之ThreadPool篇

    C# 异步多线程入门到精通之ThreadPool篇

    ThreadPool 是 .net 2.0 时代的产物,有了 Thread 为什么还会有 ThreadPool 呢?ThreadPool 可以做到限制线程数量、重用线程
    2021-11-11
  • C# Directory.GetFiles()函数案例详解

    C# Directory.GetFiles()函数案例详解

    这篇文章主要介绍了C# Directory.GetFiles()函数案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • C# 最基础知识介绍--多态

    C# 最基础知识介绍--多态

    在本篇文章将对大家介绍得是在C#中最常用的几种概念,即:多态,下面文章内容将对大家详细介绍这几种常用得状态
    2021-09-09
  • C#中结构(struct)的部分初始化和完全初始化实例分析

    C#中结构(struct)的部分初始化和完全初始化实例分析

    这篇文章主要介绍了C#中结构(struct)的部分初始化和完全初始化,通过实例分析了结构初始化中常见的错误及技巧,有助于加深对C#结构(struct)的认识,需要的朋友可以参考下
    2014-09-09

最新评论