在richtextbox中加载word文件(.docx)

时间:2015-06-09 03:17:31

标签: c# wpf text ms-word richtextbox

我已经能够将.docx文件加载到我的wpf应用程序中,但它似乎不会出现在我的richtextbox中:

if (openFile.ShowDialog() == true)
{
     // Open document 
     string originalfilename = System.IO.Path.GetFullPath(openFile.FileName);

     if (openFile.CheckFileExists)
     {
         var document = DocX.Load(originalfilename);
         string contents = document.Text;
         rtfMain.Document = contents; 

         MessageBox.Show("file loaded");
     }
} 

wpf中的richtextbox不接受内容字符串变量。知道如何让它发挥作用吗?

2 个答案:

答案 0 :(得分:1)

 if (openFile.ShowDialog() == true)
        {
            // Open document 
            string originalfilename = System.IO.Path.GetFullPath(openFile.FileName);

            if (openFile.CheckFileExists && new[] { ".docx", ".doc", ".txt", ".rtf" }.Contains(Path.GetExtension(originalfilename).ToLower()))
            {
                Microsoft.Office.Interop.Word.Application wordObject = new Microsoft.Office.Interop.Word.Application();
                object File = originalfilename;
                object nullobject = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Application wordobject = new Microsoft.Office.Interop.Word.Application();
                wordobject.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
                Microsoft.Office.Interop.Word._Document docs = wordObject.Documents.Open(ref File, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
                docs.ActiveWindow.Selection.WholeStory();
                docs.ActiveWindow.Selection.Copy();
                rtfMain.Document.Paste();
                docs.Close(ref nullobject, ref nullobject, ref nullobject);
                wordobject.Quit(ref nullobject, ref nullobject, ref nullobject);


                MessageBox.Show("file loaded");
            }
        } 

答案 1 :(得分:0)

该代码不应该编译,RichTextBox.Document的类型为FlowDocument,您将其分配给string

也许您应该寻找将 .docx 文件转换为可以分配给FlowDocument的{​​{1}}的方法。

您可以使用一种名为Word to XAML

的流行工具

另一个选择是: