





















在日常办公或系统开发中,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 中提取表格的核心思路是 逐层解析文档结构:
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。
doc.Sections 获取。section.Tables 获取。单元格 TableCell 内部可能包含多个段落(Paragraph),每个段落可能有不同的格式(加粗、颜色等)。我们只需提取纯文本内容:
cell.Paragraphs,获取每个段落的 TextTrim() 去除段落首尾空白,避免多余换行。.txt 文件,文件名包含节索引和表格索引,便于区分。\t 分隔,行末添加换行符。这种格式可直接复制到 Excel 中粘贴,或者被其他数据分析工具读取。基于本文代码,可以轻松扩展以下功能:
using Spire.Xls;
// 将 tableData 的二维数组写入 Workbook
string[] files = Directory.GetFiles(@"C:\Docs", "*.docx");
foreach (string file in files)
{
doc.LoadFromFile(file);
// ... 提取逻辑
}
\r, \n 替换为空格)将提取的表格数据转换为 DataTable,然后使用 SqlBulkCopy 批量写入 SQL Server。
通过本文介绍的方法,你可以高效地从 Word 文档中提取表格数据,为后续的数据处理提供便利。相比原生 Office Interop(需要安装 Word 且不稳定),Free Spire.Doc 无需依赖 Office 客户端,运行更轻量、稳定;代码逻辑清晰,便于复用和二次开发。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。