首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >识别docx中的第一个表,并使用c#打印其中包含表的目录中的文档

识别docx中的第一个表,并使用c#打印其中包含表的目录中的文档
EN

Stack Overflow用户
提问于 2021-01-20 16:53:50
回答 1查看 32关注 0票数 0

我需要检查一个大小约为10 GB的目录中的所有文件(特别是"*.docx"),并过滤其中包含表的文档的名称。对于目录中的每个文件,我需要遍历文件的文档元素,以确定打开的文档是否有表。我需要在C#中完成这项工作。我来自测试领域,但他们给了我开发的任务。请帮帮忙

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-20 17:19:21

您可以使用DocumentFormat.OpenXml nuget包来访问docx文件,并找到每个文件中的表。

代码语言:javascript
复制
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            var files = FindFilesWithTable("<path_to_directory>");

            foreach (var file in files)
            {
                Console.WriteLine(file);
            }
    }

    static List<string> FindFilesWithTable(string directory)
    {
        // filter all docx files
        var files = Directory.GetFiles(directory, "*.docx");
        var filesWithTable = new List<string>();
        foreach (var file in files)
        {
            try
            {
                // open file in read only mode
                using (WordprocessingDocument doc = WordprocessingDocument.Open(file, false))
                {
                    // find the first table in the document.  
                    var hasTable = doc.MainDocumentPart.Document.Body.Elements<Table>().Any();
                    if (hasTable)
                    {
                        filesWithTable.Add(file);
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Cannot process {0}: {1}", file, ex.Message);
            }
        }
        return filesWithTable;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65806081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档