栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

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

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908068.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号