我有一个带有浏览和提交按钮的视图。当用户点击浏览时,可以浏览.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文档中的文本。是我读错了文件,还是我的代码有什么问题。
我会考虑使用OpenXML SDK从Word文档中提取信息,而不是使用Word Automation,因为这需要在服务器上安装Word(这可能不是一个好主意):
http://www.microsoft.com/download/en/details.aspx?id=5124
请注意,这不适用于.doc文件,只适用于docx。
山姆,你可以在这里看到我的问题,正如我之前所问的,如果你觉得它有用的话。实际上,对于这种类型的问题,你需要自己探索类,并根据自己的情况使用它。这将为您提供基本的休息。
非常感谢朋友们的帮助。以下是我所做的,它解决了问题,
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对象。希望这是最好的方法。