使用 C# 提取 Word 文档中的表格数据

使用 C# 提取 Word 文档中的表格数据 要实现 Word 表格提取我们需要以下工具和组件开发环境Visual Studio2022/2019 等或任意 C# 开发工具第三方库Free Spire.Doc用于解析 Word 文档结构处理表格数据Free Spire.Doc 是一个免费的 Word 文档处理库支持读取、编辑、生成 Word 文档尤其对表格、段落等元素的处理非常便捷。可以通过NuGet 包管理器安装它Install-Package FreeSpire.Doc或者在项目中右键“管理 NuGet 包”搜索Spire.Doc并安装。⚠️注意免费版单文档最多支持 25 个表格适用于学习、测试和小型业务场景提取 Word 表格实现思路从 Word 中提取表格的核心思路是逐层解析文档结构加载 Word 文档获取文档对象遍历文档中的“节Section”Word 文档的基本结构单位在每个节中获取表格集合遍历所有表格对每个表格逐行、逐单元格提取文本内容将提取的表格数据按格式制表符分隔保存到文本文件完整代码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。节Section一个文档可以有多个节如不同页码格式、页眉页脚的区域。通过doc.Sections获取。表格Table每个节可以包含多个表格通过section.Tables获取。② 提取单元格文本单元格TableCell内部可能包含多个段落Paragraph每个段落可能有不同的格式加粗、颜色等。我们只需提取纯文本内容遍历cell.Paragraphs获取每个段落的 Text使用Trim()去除段落首尾空白避免多余换行。多个段落之间用空格连接保证可读性。③ 保存为文本文件每个表格单独保存为一个.txt文件文件名包含节索引和表格索引便于区分。单元格之间用制表符\t分隔行末添加换行符。这种格式可直接复制到 Excel 中粘贴或者被其他数据分析工具读取。实用扩展方向基于本文代码可以轻松扩展以下功能1. 导出为 Excel 文件使用 Free Spire.XLSusing Spire.Xls; // 将 tableData 的二维数组写入 Workbook2. 批量处理多个 Word 文档string[] files Directory.GetFiles(C:\Docs, *.docx); foreach (string file in files) { doc.LoadFromFile(file); // ... 提取逻辑 }