[英]How to check if the Word file contains text C#
我正在處理一些 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 文件都會顯示在控制台中
可以統計word文檔的字數。
if (document.Words.Count <= 0)
{
Console.WriteLine(document.Name);
}
您可以使用 Microsoft 的Open XML SDK來查找 Word 文檔中的特定元素。 這不需要在運行程序的計算機上安裝 Office。
用於查找形狀如何使用 Open 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;
}
}
可在此處找到形狀參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.