在我的应用程序中,我想读取一个文档文件(.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/