如何在Asp.Net MVC3中读取.doc和.docx文件并在TextBox中显示

时间:2012-01-20 10:03:20

标签: asp.net-mvc-3

我有一个带浏览和提交按钮的视图。当用户点击浏览时,可以浏览.doc或.docx文件,当点击提交按钮时,所选文件的文本应填入同一视图的文本框中。 下面是我的代码,用于阅读和显示TextBox中的文本。

            string filePath =null,docText=null;
            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase Infile = Request.Files[inputTagName];
                if (Infile.ContentLength > 0 && (Path.GetExtension(Infile.FileName) == ".doc"))
                {
                    filePath = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    Path.GetFileName(Infile.FileName));
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                    Infile.SaveAs(filePath);
                }
                if (filePath != null)
                {

                    docText = System.IO.File.ReadAllText(filePath);

                }
                ViewBag.displayTextInTextBox= docText;
            }
            return View();

以下是我的观看代码

<input type="text" id="test1" name="test" value="@ViewBag.displayTextInTextBox">

它显示特殊字符(如此 ࡱ )而不是.doc / .docx文档中的文本。 我正在错误地阅读文件或我的代码中存在什么问题。

3 个答案:

答案 0 :(得分:4)

而不是使用Word Automation,这需要在您的服务器上安装Word(这可能不是一个好主意),我会考虑使用OpenXML SDK从word文档中提取信息:

http://www.microsoft.com/download/en/details.aspx?id=5124

请注意,这不适用于.doc文件,只适用于docx。

答案 1 :(得分:2)

Sam,你可以看到我的问题here,正如我之前也问过的,如果你能发现它有用。 实际上对于这类问题,您需要自己探索类并根据您的需要使用它。 这个ans将为您提供必须完成的基础知识。

答案 2 :(得分:-2)

非常感谢朋友们的帮助。 以下是我所做的,它解决了问题,

Microsoft.Office.Interop.Word.ApplicationClass wordApp = new 

    Microsoft.Office.Interop.Word.ApplicationClass();
                    string filePath1 = filePath;
                    object file = filePath1;
                    object nullobj = System.Reflection.Missing.Value;

   Microsoft.Office.Interop.Word.Document doc = wordApp.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);
                 Microsoft.Office.Interop.Word.Document doc1 = wordApp.ActiveDocument;
                 string m_Content = doc1.Content.Text;
                 ViewBag.test = m_Content;
                 doc.Close(ref nullobj, ref nullobj, ref nullobj);

我正在使用MSWord的COM对象。  希望这是最好的方法。