如何使用字符串生成器读取word文档内容?

时间:2013-08-17 12:55:56

标签: c# asp.net

我已将文件上传到服务器。如何使用c#读取内容并显示它。 我使用字符串构建器来提取内容,并将其显示在多行文本框中。

我使用的代码是: -

             string[] readText = File.ReadAllLines(path);

            StringBuilder strbuild = new StringBuilder();
            foreach (string s in readText)
            {
                strbuild.Append(s);
                strbuild.AppendLine();
            }
            txtPreview.Text = strbuild.ToString();

这个问题是,在顶部和底部显示某种额外的不可读字符,可能是某种加密文本。如何删除这些字符,只显示内容?

更新: 我正在使用Microsoft Interop库,我能够将word文档的内容显示在多行文本框中。

                Microsoft.Office.Interop.Word.Document doc = Application.Documents.Open(ref file, ref nullobj, ref nullobj,
                                                  ref nullobj, ref nullobj, ref nullobj,
                                                  ref nullobj, ref nullobj, ref nullobj,
                                                  ref nullobj, ref nullobj, ref nullobj,
                                                  ref nullobj, ref nullobj, ref nullobj, ref nullobj);
                doc.Activate();
                string Doc_Content = doc.Content.Text;
                string str = Doc_Content;
                var words = str.Split(new char[] { ' ', ':', '\r', '\t' });

                for (int i = 0; i < words.Length; i++)
                {
                    string val1 = words[i].ToString();
                }

我创建了一个字符串变量str来保存word文件的所有内容。还有一个数组字[]来存储单词。 我现在面临的问题是: - 读一读。如果第一个单词是“hello”,我需要阅读第二个和第三个单词。 如果第一个单词是“hello”而第二个单词是“world”,我需要阅读第三个和第四个单词。另外,我需要阅读第一和第二个词。 怎么办呢?

1 个答案:

答案 0 :(得分:4)

Word文档不是基本文本。根据版本,它们可以是“包”(压缩的xml)或自定义二进制格式。因此,您需要破解包并读取xml(不建议)或使用库。

作为.NET框架的一部分,OpenXml将使您能够打开Word.docx文件并使用它们。 this example中有一些有用的摘录。如果您不想关注this,还可以找到Msft documentation等基础知识教程。

NPOI这样的非msft库可以帮助处理.doc.docx个文件。

要使用互操作,您需要在处理文档的服务器上安装办公室。为此目的,可以运行无头字。但是,我个人不会推荐它。