如何从 .docx/.odt/.doc 文件中读取或复制文本

How to read or copy text from .docx/.odt/.doc files

在我的应用程序中,我想读取一个文档文件(.doc 或 .odt 或 .docx)并将该文本存储在一个字符串中。为此,我使用以下代码:

string text;     
using (var streamReader = new StreamReader(@"D:\Sample\Demo.docx", System.Text.Encoding.UTF8))
{
    text = streamReader.ReadToEnd();
}

但是我无法阅读或复制正确的文本,因为它显示如下:

PK�����!��x%���E���[Content_Types].xml �(������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������IO�0��H���W��p@5��r�Jqv�Ij/�ۿg�%j��)P.���y��tf�N&�QY����0��T9���w,� L!jk gs@�л���0!����Bp�����Y�VJ�t�+���N�Kk�����z�'(Ÿ��/I��X�|/F�L騏��^��w$¹ZIho|b��tŔ�r����+?�W��6V�7*�W$}�ë�DΧ���r�i��q�=��,��Fݜ��t�5+Z(��?�a�z���i�[!0�k��,}O��Ta�\� �m?�i�|���ж�AT�SB�;'m;y�"La��o� %��@k8��?,Fc� hL_\��̱�9I����!�=��m��TT���|P�̩}}�$�|��� ��=�|��}�����PK��

如何从文档文件中读取或复制文本?

Microsoft DocX 格式是一个容器,不以简单明文形式保存数据(您的 StreamReader 尝试读取。

您应该考虑使用如下第三方库:https://docx.codeplex.com/

为此你需要使用不同的库

使用 Microsoft.Office.Interop.Word

从 Word 文档中读取数据的示例
using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main()
    {
    // Open a doc file.
    Application application = new Application();
    Document document = application.Documents.Open("C:\word.doc");

    // Loop through all words in the document.
    int count = document.Words.Count;
    for (int i = 1; i <= count; i++)
    {
        // Write the word.
        string text = document.Words[i].Text;
        Console.WriteLine("Word {0} = {1}", i, text);
    }
    // Close word.
    application.Quit();
    }
}

Microsoft.Office.Interop.Word 对于大文档来说非常慢。所以我建议 OpenXml。对于使用 OpenXml,您应该安装它。

  1. 使用包管理器安装:

    安装包 DocumentFormat.OpenXml - 版本 2.8.1

2.Use OpenWordprocessingDocumentReadonly 函数:

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace Readdocx
{
    class Program
    {
        static void Main(string[] args)
        {
            string mytext = OpenWordprocessingDocumentReadonly("mytext.docx");
        }
        public static string OpenWordprocessingDocumentReadonly(string filepath)
        {
            // Open a WordprocessingDocument based on a filepath.
            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Open(filepath, false))
            {
                // Assign a reference to the existing document body.  
                Body body = wordDocument.MainDocumentPart.Document.Body;
                //text of Docx file 
                return body.InnerText.ToString();
             }
            return "-1";
        }
    }
}