如何解决识别docx中的第一个表并使用c#打印目录中包含表的文档
我需要检查大小约为 10 GB 的目录中的所有文件(尤其是“*.docx”),并过滤包含表格的文档名称。对于目录中的每个文件,我需要遍历文件的 Document 元素以找出打开的文档是否有表格。我需要在 C# 中完成这项工作。我来自测试领域,但他们给了我开发类任务。请帮忙
解决方法
您可以使用 DocumentFormat.OpenXml
nuget 包访问 docx 文件并在每个文件中查找表。
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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。