C#如何读取带格式的word文档内容

背景

最近接到个需求,需要把word文档原汁原味的复制出来,在对文档内容进行解析。

开始采用的方式是打开文档,直接读取。经过测试发现内容都是无格式的。这显然不是想要的。

后面转变思路一想,既然人工打开文档,全选复制,在黏贴到其他文档是带格式的,那么完全可以使用代码把人工的事情做一遍。.

代码实现

1、用richTextBox打开带格式的word文档

  Microsoft.Office.Interop.Word.ApplicationClass app = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document doc = null;
            object missing = System.Reflection.Missing.Value;
            object File = fileName;
            object readOnly = false;
            object isVisible = true;
            try
            {
                doc = app.Documents.Open(ref File, ref missing, ref readOnly,
                 ref missing, ref missing, ref missing, ref missing, ref missing,
                 ref missing, ref missing, ref missing, ref isVisible, ref missing,
                 ref missing, ref missing, ref missing);

2、全选其中的内容并保存的剪切板中

    doc.ActiveWindow.Selection.WholeStory();//全选word文档中的数据
                doc.ActiveWindow.Selection.Copy();//复制数据到剪切板

3、最后在richTextBox中粘贴数据,并关闭文档

richTextBox1.Paste();//richTextBox粘贴数据
                SetText(null);
                //richTextBox1.Text = doc.Content.Text;//显示无格式数据
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close(ref missing, ref missing, ref missing);
                    doc = null;
                }

                if (app != null)
                {
                    app.Quit(ref missing, ref missing, ref missing);
                    app = null;
                }
            }

总结

用richTextBox打开带格式的word文档。先打开word文档,全选其中的内容并保存的剪切板中,最后在richTextBox中粘贴数据,并关闭文档。