最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實(shí)現(xiàn)提取Word文檔中的表格數(shù)據(jù)

 更新時(shí)間:2026年04月21日 08:21:21   作者:LAYONTHEGROUND  
在日常辦公或系統(tǒng)開發(fā)中,Word?文檔里的表格數(shù)據(jù)常常需要被提取出來,本文將展示如何使用?C#?搭配?Free?Spire.Doc?庫,無需安裝?Microsoft?Word,即可快速、穩(wěn)定地提取?Word?表格內(nèi)容,并導(dǎo)出為結(jié)構(gòu)化的文本文件,感興趣的小伙伴可以了解下

在日常辦公或系統(tǒng)開發(fā)中,Word 文檔里的表格數(shù)據(jù)常常需要被提取出來,用于數(shù)據(jù)導(dǎo)入、統(tǒng)計(jì)分析或報(bào)表生成。然而,手動(dòng)復(fù)制粘貼效率低下,而借助 Office COM 組件又容易遇到版本兼容、部署繁瑣等問題。本文將展示如何使用 C# 搭配 Free Spire.Doc 庫,無需安裝 Microsoft Word,即可快速、穩(wěn)定地提取 Word 表格內(nèi)容,并導(dǎo)出為結(jié)構(gòu)化的文本文件。

工具與環(huán)境準(zhǔn)備

要實(shí)現(xiàn) Word 表格提取,我們需要以下工具和組件:

  • 開發(fā)環(huán)境:Visual Studio(2022/2019 等)或任意 C# 開發(fā)工具
  • 第三方庫:Free Spire.Doc(用于解析 Word 文檔結(jié)構(gòu),處理表格數(shù)據(jù))

Free Spire.Doc 是一個(gè)免費(fèi)的 Word 文檔處理庫,支持讀取、編輯、生成 Word 文檔,尤其對(duì)表格、段落等元素的處理非常便捷??梢酝ㄟ^ NuGet 包管理器 安裝它:

Install-Package FreeSpire.Doc

或者在項(xiàng)目中右鍵“管理 NuGet 包”,搜索 Spire.Doc 并安裝。

注意:免費(fèi)版單文檔最多支持 25 個(gè)表格,適用于學(xué)習(xí)、測(cè)試和小型業(yè)務(wù)場(chǎng)景

提取 Word 表格實(shí)現(xiàn)思路

從 Word 中提取表格的核心思路是 逐層解析文檔結(jié)構(gòu)

  1. 加載 Word 文檔,獲取文檔對(duì)象
  2. 遍歷文檔中的“節(jié)(Section)”(Word 文檔的基本結(jié)構(gòu)單位)
  3. 在每個(gè)節(jié)中獲取表格集合,遍歷所有表格
  4. 對(duì)每個(gè)表格,逐行、逐單元格提取文本內(nèi)容
  5. 將提取的表格數(shù)據(jù)按格式(制表符分隔)保存到文本文件

完整代碼

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)
        {
            // 創(chuàng)建文檔對(duì)象
            Document doc = new Document();
            // 加載Word文檔
            doc.LoadFromFile("表格.docx");
            // 遍歷文檔中的所有節(jié)
            for (int sectionIndex = 0; sectionIndex < doc.Sections.Count; sectionIndex++)
            {
                Section section = doc.Sections[sectionIndex];
                // 獲取當(dāng)前節(jié)中的所有表格
                TableCollection tables = section.Tables;
                // 遍歷當(dāng)前節(jié)中的所有表格
                for (int tableIndex = 0; tableIndex < tables.Count; tableIndex++)
                {
                    ITable table = tables[tableIndex];
                    // 用于存儲(chǔ)當(dāng)前表格的所有數(shù)據(jù)
                    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];
                            // 提取單元格文本(單元格可能包含多個(gè)段落)
                            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";
                            }
                        }
                        // 行結(jié)束后換行
                        tableData += "\n";
                    }
                    // 保存表格數(shù)據(jù)到文本文件)
                    string filePath = Path.Combine("Tables", $"Section{sectionIndex + 1}_Table{tableIndex + 1}.txt");
                    File.WriteAllText(filePath, tableData, Encoding.UTF8);
                }
            }
            doc.Close();
        }
    }
}

代碼核心邏輯解析

遍歷文檔結(jié)構(gòu)

Word 文檔的邏輯結(jié)構(gòu)是:Document → Section → Table → Row → Cell。

  • 節(jié)(Section):一個(gè)文檔可以有多個(gè)節(jié)(如不同頁碼格式、頁眉頁腳的區(qū)域)。通過 doc.Sections 獲取。
  • 表格(Table):每個(gè)節(jié)可以包含多個(gè)表格,通過 section.Tables 獲取。

提取單元格文本

單元格 TableCell 內(nèi)部可能包含多個(gè)段落(Paragraph),每個(gè)段落可能有不同的格式(加粗、顏色等)。我們只需提取純文本內(nèi)容:

  • 遍歷 cell.Paragraphs,獲取每個(gè)段落的 Text
  • 使用 Trim() 去除段落首尾空白,避免多余換行。
  • 多個(gè)段落之間用空格連接,保證可讀性。

保存為文本文件

  • 每個(gè)表格單獨(dú)保存為一個(gè) .txt 文件,文件名包含節(jié)索引和表格索引,便于區(qū)分。
  • 單元格之間用 制表符 \t 分隔,行末添加換行符。這種格式可直接復(fù)制到 Excel 中粘貼,或者被其他數(shù)據(jù)分析工具讀取。

實(shí)用擴(kuò)展方向

基于本文代碼,可以輕松擴(kuò)展以下功能:

導(dǎo)出為 Excel 文件(使用 Free Spire.XLS)

using Spire.Xls;
// 將 tableData 的二維數(shù)組寫入 Workbook

批量處理多個(gè) Word 文檔

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

文本清洗與格式化

  • 去除特殊符號(hào)(如 \r, \n 替換為空格)
  • 統(tǒng)一數(shù)字格式(如貨幣符號(hào)、百分比)
  • 使用正則表達(dá)式過濾無關(guān)字符

直接導(dǎo)入數(shù)據(jù)庫

將提取的表格數(shù)據(jù)轉(zhuǎn)換為 DataTable,然后使用 SqlBulkCopy 批量寫入 SQL Server。

方法補(bǔ)充

OpenXML SDK(開源免費(fèi),高性能)

OpenXML SDK 是微軟官方的開源庫,直接操作 .docx 文件的底層 XML 結(jié)構(gòu),無需安裝 Office,在服務(wù)器端也能高性能處理,是其核心優(yōu)勢(shì)。

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; }
    // 可根據(jù)需要擴(kuò)展行列信息
}
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;
}

關(guān)鍵要點(diǎn):使用 OpenXML SDK 時(shí),可通過 WordprocessingDocument.Open() 打開文檔,第二個(gè)參數(shù) isEditable 設(shè)置為 false 表示只讀,以提升性能。核心是遍歷 Body 中的 Table 元素及其子元素 TableRow 和 TableCell,最終通過 InnerText 獲取單元格文本。

Spire.Doc(商業(yè)庫,API 極簡(jiǎn))

Spire.Doc 的 API 設(shè)計(jì)直觀,核心邏輯是先加載文檔,再通過 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))
    {
        // 遍歷文檔的所有節(jié)
        for (int sectionIdx = 0; sectionIdx < doc.Sections.Count; sectionIdx++)
        {
            Section section = doc.Sections[sectionIdx];
            TableCollection tables = section.Tables;
            // 遍歷每個(gè)表格
            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() 方法,可用于處理復(fù)雜的合并單元格場(chǎng)景。

GroupDocs.Parser(商業(yè)庫,跨格式統(tǒng)一)

GroupDocs.Parser 將表格提取抽象為統(tǒng)一 API,支持從 PDF、DOCX、XLSX 等多種格式中提取表格,特別適合需要處理混合文件類型的項(xiàng)目。

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;
        }
        // 獲取表格數(shù)據(jù)
        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("---");
        }
    }
}

高級(jí)配置:可通過 TemplateTableLayout 精確指定列寬和行高,適應(yīng)復(fù)雜或非標(biāo)準(zhǔn)結(jié)構(gòu)的表格提取。

總結(jié)

通過本文介紹的方法,你可以高效地從 Word 文檔中提取表格數(shù)據(jù),為后續(xù)的數(shù)據(jù)處理提供便利。相比原生 Office Interop(需要安裝 Word 且不穩(wěn)定),F(xiàn)ree Spire.Doc 無需依賴 Office 客戶端,運(yùn)行更輕量、穩(wěn)定;代碼邏輯清晰,便于復(fù)用和二次開發(fā)。

到此這篇關(guān)于C#實(shí)現(xiàn)提取Word文檔中的表格數(shù)據(jù)的文章就介紹到這了,更多相關(guān)C#提取Word表格數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

土默特右旗| 长顺县| 博湖县| 临潭县| 乾安县| 长宁区| 修水县| 巨野县| 吴忠市| 兴安盟| 佛教| 中宁县| 浪卡子县| 徐水县| 东丽区| 泾阳县| 曲阜市| 浠水县| 滦平县| 溆浦县| 锦屏县| 建平县| 沙坪坝区| 利辛县| 松潘县| 扎兰屯市| 措勤县| 汾阳市| 东至县| 瑞金市| 吴川市| 大同县| 齐齐哈尔市| 娱乐| 巴彦县| 新建县| 长沙县| 敦煌市| 阜康市| 新龙县| 凭祥市|