load word file (.docx) in richtextbox

人走茶凉 提交于 2020-01-06 03:08:11

问题


I was already able to load a .docx file into my wpf application but it doesn't seem to show up in my 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");
     }
} 

The contents string variable is not accepted by the richtextbox in wpf. Any idea how to make it work?


回答1:


That code shouldn't compile, RichTextBox.Document is of type FlowDocument, and you are assigning it to a string.

Maybe you should look for ways to convert a .docx file to a FlowDocument you can assign to the RichTextBox.

There is a popular tool you can use which is called: Word to XAML

Another options are:

  • OpenXML + FlowDocument = OpenFlowDocument?
  • Show Word file in WPF



回答2:


 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");
            }
        } 


来源:https://stackoverflow.com/questions/30722434/load-word-file-docx-in-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!