如何检查Word文件是否包含文本c#
本文关键字:是否 文件 包含 文本 Word 何检查 检查 | 更新日期: 2023-09-27 18:13:36
我正在处理一些word文件,现在我想看看正在处理的文件是否包含其他东西,然后"形状"在我的情况下,这将是普通的文本
我知道如何检测文件是否包含形状等。但是要查看文档是否包含文本我不确定该怎么做
string path = "C:/Users/Test/Desktop/Test/";
foreach (string file in Directory.EnumerateFiles(path, "*.docx"))
{
var fileInfo = new FileInfo(file);
if (!fileInfo.Name.StartsWith("~$"))
{
var wordApplication = new Microsoft.Office.Interop.Word.Application();
var document = wordApplication.Documents.Open(file);
if (document.Content.Text.Contains(""))
{
Console.WriteLine(document.Name);
}
}
可能是这样的如果文档不包含任何内容?
即使我输入一个有文本和没有文本的word文件也会显示在控制台
您可以计算word文档中的单词数。
if (document.Words.Count <= 0)
{
Console.WriteLine(document.Name);
}
您可以使用Microsoft的Open XML SDK来查找Word文档中的特定元素。这并不需要在运行程序的机器上安装Office。
寻找形状如何在使用开放XML SDK的SdtBlock元素中获得形状列表?给出了一个很好的示例:
给你一个想法,你可以很容易地遍历所有元素,就像这个例子一样,来决定Word文件是否适合处理。请注意,这段代码只是大致的想法。
var package = WordprocessingDocument.Open(wordFileStream, false);
OpenXmlElement element = package.MainDocumentPart.Document.Body;
foreach (OpenXmlElement section in element.Elements())
{
switch (section.LocalName)
{
// Text
case "t":
// we have found text
break;
case "cr": // Carriage return
case "br": // Page break
// we have found carriage return or page break
break;
case "p":
// we have found a paragraph
break;
default:
// we have found something else
break;
}
}
shape的参考在这里