C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#提取Word表格数据

C#实现提取Word文档中的表格数据

作者:LAYONTHEGROUND

在日常办公或系统开发中,Word 文档里的表格数据常常需要被提取出来,本文将展示如何使用 C# 搭配 Free Spire.Doc 库,无需安装 Microsoft Word,即可快速、稳定地提取 Word 表格内容,并导出为结构化的文本文件,感兴趣的小伙伴可以了解下

在日常办公或系统开发中,Word 文档里的表格数据常常需要被提取出来,用于数据导入、统计分析或报表生成。然而,手动复制粘贴效率低下,而借助 Office COM 组件又容易遇到版本兼容、部署繁琐等问题。本文将展示如何使用 C# 搭配 Free Spire.Doc 库,无需安装 Microsoft Word,即可快速、稳定地提取 Word 表格内容,并导出为结构化的文本文件。

工具与环境准备

要实现 Word 表格提取,我们需要以下工具和组件:

Free Spire.Doc 是一个免费的 Word 文档处理库,支持读取、编辑、生成 Word 文档,尤其对表格、段落等元素的处理非常便捷。可以通过 NuGet 包管理器 安装它:

Install-Package FreeSpire.Doc

或者在项目中右键“管理 NuGet 包”,搜索 Spire.Doc 并安装。

注意:免费版单文档最多支持 25 个表格,适用于学习、测试和小型业务场景

提取 Word 表格实现思路

从 Word 中提取表格的核心思路是 逐层解析文档结构

  1. 加载 Word 文档,获取文档对象
  2. 遍历文档中的“节(Section)”(Word 文档的基本结构单位)
  3. 在每个节中获取表格集合,遍历所有表格
  4. 对每个表格,逐行、逐单元格提取文本内容
  5. 将提取的表格数据按格式(制表符分隔)保存到文本文件

完整代码

using Spire.Doc;
using Spire.Doc.Collections;
using Spire.Doc.Interface;
using System.IO;
using System.Text;
namespace ExtractWordTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建文档对象
            Document doc = new Document();
            // 加载Word文档
            doc.LoadFromFile("表格.docx");
            // 遍历文档中的所有节
            for (int sectionIndex = 0; sectionIndex < doc.Sections.Count; sectionIndex++)
            {
                Section section = doc.Sections[sectionIndex];
                // 获取当前节中的所有表格
                TableCollection tables = section.Tables;
                // 遍历当前节中的所有表格
                for (int tableIndex = 0; tableIndex < tables.Count; tableIndex++)
                {
                    ITable table = tables[tableIndex];
                    // 用于存储当前表格的所有数据
                    string tableData = "";
                    // 遍历表格中的所有行
                    for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
                    {
                        TableRow row = table.Rows[rowIndex];
                        // 遍历行中的所有单元格
                        for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
                        {
                            TableCell cell = row.Cells[cellIndex];
                            // 提取单元格文本(单元格可能包含多个段落)
                            string cellText = "";
                            for (int paraIndex = 0; paraIndex < cell.Paragraphs.Count; paraIndex++)
                            {
                                cellText += (cell.Paragraphs[paraIndex].Text.Trim() + " ");
                            }
                            // 拼接单元格文本,用制表符分隔不同单元格
                            tableData += cellText.Trim();
                            if (cellIndex < row.Cells.Count - 1)
                            {
                                tableData += "\t";
                            }
                        }
                        // 行结束后换行
                        tableData += "\n";
                    }
                    // 保存表格数据到文本文件)
                    string filePath = Path.Combine("Tables", $"Section{sectionIndex + 1}_Table{tableIndex + 1}.txt");
                    File.WriteAllText(filePath, tableData, Encoding.UTF8);
                }
            }
            doc.Close();
        }
    }
}

代码核心逻辑解析

遍历文档结构

Word 文档的逻辑结构是:Document → Section → Table → Row → Cell

提取单元格文本

单元格 TableCell 内部可能包含多个段落(Paragraph),每个段落可能有不同的格式(加粗、颜色等)。我们只需提取纯文本内容:

保存为文本文件

实用扩展方向

基于本文代码,可以轻松扩展以下功能:

导出为 Excel 文件(使用 Free Spire.XLS)

using Spire.Xls;
// 将 tableData 的二维数组写入 Workbook

批量处理多个 Word 文档

string[] files = Directory.GetFiles(@"C:\Docs", "*.docx");
foreach (string file in files)
{
    doc.LoadFromFile(file);
    // ... 提取逻辑
}

文本清洗与格式化

直接导入数据库

将提取的表格数据转换为 DataTable,然后使用 SqlBulkCopy 批量写入 SQL Server。

方法补充

OpenXML SDK(开源免费,高性能)

OpenXML SDK 是微软官方的开源库,直接操作 .docx 文件的底层 XML 结构,无需安装 Office,在服务器端也能高性能处理,是其核心优势。

1. 安装 NuGet 包

Install-Package DocumentFormat.OpenXml

2. 读取表格的示例代码

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
public class TableData
{
    public string CellText { get; set; }
    // 可根据需要扩展行列信息
}
public static List<List<string>> ExtractTablesFromWord(string filePath)
{
    var allTables = new List<List<string>>();
    using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, false))
    {
        // 获取文档主体
        Body body = doc.MainDocumentPart.Document.Body;
        // 遍历所有表格
        IEnumerable<DocumentFormat.OpenXml.Wordprocessing.Table> tables = body.Elements<DocumentFormat.OpenXml.Wordprocessing.Table>();
        foreach (var table in tables)
        {
            var tableData = new List<string>();
            // 遍历所有行
            foreach (TableRow row in table.Elements<TableRow>())
            {
                // 遍历所有单元格
                foreach (TableCell cell in row.Elements<TableCell>())
                {
                    // 获取单元格文本
                    string cellText = cell.InnerText;
                    tableData.Add(cellText);
                }
            }
            allTables.Add(tableData);
        }
    }
    return allTables;
}

关键要点:使用 OpenXML SDK 时,可通过 WordprocessingDocument.Open() 打开文档,第二个参数 isEditable 设置为 false 表示只读,以提升性能。核心是遍历 Body 中的 Table 元素及其子元素 TableRow 和 TableCell,最终通过 InnerText 获取单元格文本。

Spire.Doc(商业库,API 极简)

Spire.Doc 的 API 设计直观,核心逻辑是先加载文档,再通过 Section.Tables 获取表格集合,然后逐层访问行、单元格和段落文本。

1. 安装 NuGet 包

Install-Package Spire.Doc

2. 提取表格并保存到文本文件的代码

using Spire.Doc;
using Spire.Doc.Collections;
using System.Text;
public static void ExtractTablesWithSpire(string docPath, string outputPath)
{
    Document doc = new Document();
    doc.LoadFromFile(docPath);
    using (StreamWriter writer = new StreamWriter(outputPath))
    {
        // 遍历文档的所有节
        for (int sectionIdx = 0; sectionIdx < doc.Sections.Count; sectionIdx++)
        {
            Section section = doc.Sections[sectionIdx];
            TableCollection tables = section.Tables;
            // 遍历每个表格
            for (int tableIdx = 0; tableIdx < tables.Count; tableIdx++)
            {
                ITable table = tables[tableIdx] as ITable;
                writer.WriteLine($"--- 表格 {tableIdx + 1} ---");
                // 遍历每一行
                for (int rowIdx = 0; rowIdx < table.Rows.Count; rowIdx++)
                {
                    TableRow row = table.Rows[rowIdx];
                    StringBuilder rowText = new StringBuilder();
                    // 遍历每一列的单元格
                    for (int cellIdx = 0; cellIdx < row.Cells.Count; cellIdx++)
                    {
                        TableCell cell = row.Cells[cellIdx];
                        // 获取单元格文本
                        string cellText = "";
                        for (int pIdx = 0; pIdx < cell.Paragraphs.Count; pIdx++)
                        {
                            cellText += cell.Paragraphs[pIdx].Text;
                        }
                        rowText.Append(cellText).Append("\t");
                    }
                    writer.WriteLine(rowText.ToString().TrimEnd('\t'));
                }
            }
        }
    }
}

处理合并单元格:Spire.Doc 提供了 Table.ApplyHorizontalMerge() 和 Table.ApplyVerticalMerge() 方法,可用于处理复杂的合并单元格场景。

GroupDocs.Parser(商业库,跨格式统一)

GroupDocs.Parser 将表格提取抽象为统一 API,支持从 PDF、DOCX、XLSX 等多种格式中提取表格,特别适合需要处理混合文件类型的项目。

1. 安装 NuGet 包

Install-Package GroupDocs.Parser

2. 提取表格的示例代码

using GroupDocs.Parser;
using GroupDocs.Parser.Data;
using System;
using System.Collections.Generic;
public static void ExtractTablesWithGroupDocs(string filePath)
{
    using (Parser parser = new Parser(filePath))
    {
        // 检查文档是否支持表格提取
        if (!parser.Features.Tables)
        {
            Console.WriteLine("此文档类型不支持表格提取。");
            return;
        }
        // 获取表格数据
        IEnumerable<PageTableArea> tables = parser.GetTables();
        foreach (PageTableArea table in tables)
        {
            Console.WriteLine($"表格位置: 第 {table.Page.Index} 页");
            // 遍历所有行
            for (int row = 0; row < table.RowCount; row++)
            {
                for (int col = 0; col < table.ColumnCount; col++)
                {
                    PageTableAreaCell cell = table[row, col];
                    if (cell != null)
                    {
                        Console.Write(cell.Text?.Trim() ?? "");
                    }
                    Console.Write("\t");
                }
                Console.WriteLine();
            }
            Console.WriteLine("---");
        }
    }
}

高级配置:可通过 TemplateTableLayout 精确指定列宽和行高,适应复杂或非标准结构的表格提取。

总结

通过本文介绍的方法,你可以高效地从 Word 文档中提取表格数据,为后续的数据处理提供便利。相比原生 Office Interop(需要安装 Word 且不稳定),Free Spire.Doc 无需依赖 Office 客户端,运行更轻量、稳定;代码逻辑清晰,便于复用和二次开发。

到此这篇关于C#实现提取Word文档中的表格数据的文章就介绍到这了,更多相关C#提取Word表格数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文