您的位置:首页 > 其它

使用COM组件读写word文档

2013-05-14 18:21 489 查看
引用组件:
在菜单栏选择“项目”-“添加引用”,弹出的窗口中我们可以选择“COM”选项卡,找到Microsoft Office 12.0 Object Library(Office 2003/2007需要使用12.0版的,如果你使用的是Office 2000或者更低的版本,只要载入10.0版的就可以了),确定后引入

先看一下Word对像模型
Application :用来表现WORD应用程序,包含其它所有对象。他的成员经常应用于整个WORD,你可以用它的属性和方法控制WORD环境。
Document :Document对象是WORD编程的核心。当你打开一个已有的文档或创建一个新的文档时,就创建了一个新的Document对象, 新创建的Document将会被添加到Word Documents Collection。
Selection :Selection对象是描述当前选中的区域。若选择区域为空,则认为是当前光标处。
Rang :是Document的连续部分,根据起始字符和结束字符定义位置。
Bookmark:类似于Rang,但Bookmark可以有名字并在保存Document时Bookmark也被保存

protected void EditFile(string Source)    //修改文件
    {
        Source = Server.MapPath(Source);
       

        //定义打开文件的16个参数

        object fileName = Source; //文件名称

       

        object ConfirmConversions = false; //允许转换

        object ReadOnly = false; //只读方式打开

        object AddToRecentFiles = false; //添加到最近打开的文档

        object PasswordDocument = System.Type.Missing;

        object PasswordTemplate = System.Type.Missing;

        object Revert = System.Type.Missing;

        object WritePasswordDocument = System.Type.Missing;

        object WritePasswordTemplate = System.Type.Missing;

        object Format = System.Type.Missing; //格式

        object Encoding = System.Type.Missing; //编码

        object Visible = System.Type.Missing;

        object OpenAndRepair = System.Type.Missing;

        object DocumentDirection = System.Type.Missing;

        object NoEncodingDialog = System.Type.Missing;

        object XMLTransform = System.Type.Missing;

        Object Nothing = System.Reflection.Missing.Value;
        Word.Application wordApp = new Word.Application();     实例化一个word application对象
        Word.Document opendoc = wordApp.Documents.Open(ref fileName, ref ConfirmConversions, ref ReadOnly, ref AddToRecentFiles,  ref PasswordDocument, ref PasswordTemplate, ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate,ref Format, ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection, ref NoEncodingDialog, ref XMLTransform);打开一个word文档
        opendoc.Activate();   //激活文档,使文档为当前处理
        string str=opendoc.Content.Text;       //读出word文档
        opendoc.Close(ref Nothing, ref Nothing, ref Nothing);  //关闭文档对象

        
        
        str = str.Replace("<br>","");
        Word.Document Newdoc = wordApp.Documents.Add(ref Nothing, ref Nothing,ref Nothing, ref Nothing);  //创建一个word文档
        Newdoc.Content.Text = str;              //写入word文档
        Newdoc.SaveAs(ref fileName, ref Format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
        //关闭wordDoc文档对象
        Newdoc.Close(ref Nothing, ref Nothing, ref Nothing);
        //关闭wordApp组件对象
        wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: