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

标签 c# .net doc

在我的应用程序中,我想读取一个文档文件(.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\9�"La��o� %��@k8��?,Fc� hL_\��̱�9I����!�=��m��TT���|P�̩}}�$�|��� ��=�|��}�����PK��

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

最佳答案

为此你需要使用不同的库

使用 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();
    }
}

关于c# - 如何从 .docx/.odt/.doc 文件中读取或复制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37072832/

相关文章:

c# - Unity Compute Shaders顶点索引错误

python - 无法在 python 中为终端命令运行 '>'

.net - 指示 IEnumerable 是 "slow"或 "fast"的好方法是什么?

java - Apache POI Zip 文件已关闭

go - 解析 .doc 和 .docx 以使用 golang 获取所有文本?

c# - 如何在 Mono 和多个平台上使用 X509Certificate2 正确验证 SSL 证书

c# - 在没有 Json.Net 的情况下反序列化 Json 字符串(在 C# 中)

c# - 使用自定义属性对 FieldList 进行排序

c# - LINQ to xml - 如何选择特定节点?

c# - 我可以将 ComboBox 和简单的 Button 嵌入到 WinForms 中的 StatusStrip 中吗?