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

≯℡__Kan透↙ 提交于 2019-12-23 17:51:02

问题


In my application, I want to read a document file (.doc or .odt or .docx) and store that text in a string. For that, I am using the code below:

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

But I am unable to read or copy proper text, as it shows like:

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��

How can I read or copy text from document files?


回答1:


For that you need to use different libraries

Example for reading data from Word document using Microsoft.Office.Interop.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();
    }
}



回答2:


The Microsoft DocX-Format is a container and does not hold the data in simple plaintext (which your StreamReader tries to read.

You should consider using a third-party-library like the following: https://docx.codeplex.com/



来源:https://stackoverflow.com/questions/37072832/how-to-read-or-copy-text-from-docx-odt-doc-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!