winForm读取word内容并在窗口中呈现

在winform中读取word内容,可以通过富文本框richtextbox来实现。

读取word,首先要添加引用。点击添加引用,在com组件中添加Microsoft Word 16.0 Object. Library(我用的是office16版)
添加引用:

using Microsoft.Office;
using MSWord = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;

添加button控件和richtextbox控件,
button_click事件:

OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "word文件|*.docx";
            object fileName = 0;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                fileName = dlg.FileName;
            }
            string str = (string)fileName;
            OpenWord(str);

openword方法:

        public void OpenWord(string fileName)
        {
            MSWord.Application app = new MSWord.Application();//可以打开word
            MSWord.Document doc = null;      //需要记录打开的word

            object missing = System.Reflection.Missing.Value;
            object File = fileName;
            object readOnly = false;//不是只读
            object isVisible = true;

            object unknow = Type.Missing;

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

                doc.ActiveWindow.Selection.WholeStory();//全选word文档中的数据
                doc.ActiveWindow.Selection.Copy();//复制数据到剪切板
                richTextBox1.Paste();//richTextBox粘贴数据
                                     //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;
                }
            }
        }

代码示例地址:

https://download.csdn.net/download/qq_42002500/12670698
  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值