/***************************************************************************
 * word辅助类
 * 作者:chengfellow
 * 日期:2008.8.18
 * 注意事项:
 * 1、开发环境居于office 2003;
 * 2、需要添加Com引用:Microsoft Office 11.0 Object Library和
 *    Microsoft Word 11.0 Object Library。
 * 
 ****************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace WordAddinSample
{
    public class WordHelp
    {
        private Microsoft.Office.Interop.Word.ApplicationClass oWordApplic;    // a reference to Word application
        private Microsoft.Office.Interop.Word.Document oDoc;                    // a reference to the document
        object missing = System.Reflection.Missing.Value;

public Microsoft.Office.Interop.Word.ApplicationClass WordApplication
        {
            get { return oWordApplic; }
        }

public WordHelp()
        {
            // activate the interface with the COM object of Microsoft Word
            oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
        }

public WordHelp(Microsoft.Office.Interop.Word.ApplicationClass wordapp)
        {
            oWordApplic = wordapp;
        }

#region 文件操作

// Open a file (the file must exists) and activate it
        public void Open(string strFileName)
        {
            object fileName = strFileName;
            object readOnly = false;
            object isVisible = true;

oDoc = oWordApplic.Documents.Open(ref fileName, 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);

oDoc.Activate();
        }

// Open a new document
        public void Open()
        {
            oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);

oDoc.Activate();
        }

public void Quit()
        {
            oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
        }

/// <summary>
        /// 附加dot模版文件
        /// </summary>
        private void LoadDotFile(string strDotFile)
        {
            if (!string.IsNullOrEmpty(strDotFile))
            {
                Microsoft.Office.Interop.Word.Document wDot = null;
                if (oWordApplic != null)
                {
                    oDoc = oWordApplic.ActiveDocument;

oWordApplic.Selection.WholeStory();

//string strContent = oWordApplic.Selection.Text;

oWordApplic.Selection.Copy();
                    wDot = CreateWordDocument(strDotFile, true);

object bkmC = "Content";

if (oWordApplic.ActiveDocument.Bookmarks.Exists("Content") == true)
                    {
                        oWordApplic.ActiveDocument.Bookmarks.get_Item
                        (ref bkmC).Select();
                    }

//对标签"Content"进行填充
                    //直接写入内容不能识别表格什么的
                    //oWordApplic.Selection.TypeText(strContent);
                    oWordApplic.Selection.Paste();
                    oWordApplic.Selection.WholeStory();
                    oWordApplic.Selection.Copy();
                    wDot.Close(ref missing, ref missing, ref missing);

oDoc.Activate();
                    oWordApplic.Selection.Paste();

}
            }
        }

///  
        /// 打开Word文档,并且返回对象oDoc
        /// 完整Word文件路径+名称  
        /// 返回的Word.Document oDoc对象 
        public Microsoft.Office.Interop.Word.Document CreateWordDocument(string FileName, bool HideWin)
        {
            if (FileName == "") return null;

oWordApplic.Visible = HideWin;
            oWordApplic.Caption = "";
            oWordApplic.Options.CheckSpellingAsYouType = false;
            oWordApplic.Options.CheckGrammarAsYouType = false;

Object filename = FileName;
            Object ConfirmConversions = false;
            Object ReadOnly = true;
            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;
            try
            {
                Microsoft.Office.Interop.Word.Document wordDoc = oWordApplic.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);
                return wordDoc;

}
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

public void SaveAs(Microsoft.Office.Interop.Word.Document oDoc, string strFileName)
        {
            object fileName = strFileName;
            if (File.Exists(strFileName))
            {
                if (MessageBox.Show("文件'" + strFileName + "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    oDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                }
                else
                {
                    Clipboard.Clear();
                }
            }
            else
            {
                oDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            }
        }

public void SaveAsHtml(Microsoft.Office.Interop.Word.Document oDoc, string strFileName)
        {
            object fileName = strFileName;

//wdFormatWebArchive保存为单个网页文件
            //wdFormatFilteredHTML保存为过滤掉word标签的htm文件,缺点是有图片的话会产生网页文件夹
            if (File.Exists(strFileName))
            {
                if (MessageBox.Show("文件'" + strFileName + "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;
                    oDoc.SaveAs(ref fileName, ref Format, ref missing, ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                }
                else
                {
                    Clipboard.Clear();
                }
            }
            else
            {
                object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;
                oDoc.SaveAs(ref fileName, ref Format, ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            }
        }

public void Save()
        {
            oDoc.Save();
        }

public void SaveAs(string strFileName)
        {
            object fileName = strFileName;

oDoc.SaveAs(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        }

// Save the document in HTML format
        public void SaveAsHtml(string strFileName)
        {
            object fileName = strFileName;
            object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
            oDoc.SaveAs(ref fileName, ref Format, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        }

#endregion

#region 添加菜单(工具栏)项

//添加单独的菜单项
        public void AddMenu(Microsoft.Office.Core.CommandBarPopup popuBar)
        {
            Microsoft.Office.Core.CommandBar menuBar = null;
            menuBar = this.oWordApplic.CommandBars["Menu Bar"];
            popuBar = (Microsoft.Office.Core.CommandBarPopup)this.oWordApplic.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlPopup, missing, popuBar.Tag, true);
            if (popuBar == null)
            {
                popuBar = (Microsoft.Office.Core.CommandBarPopup)menuBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlPopup, missing, missing, missing, missing);
            }
        }

//添加单独工具栏
        public void AddToolItem(string strBarName,string strBtnName)
        {
            Microsoft.Office.Core.CommandBar toolBar = null;
            toolBar = (Microsoft.Office.Core.CommandBar)this.oWordApplic.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, missing, strBarName, true);
            if (toolBar == null)
            {
                toolBar = (Microsoft.Office.Core.CommandBar)this.oWordApplic.CommandBars.Add(
                     Microsoft.Office.Core.MsoControlType.msoControlButton,
                     missing, missing, missing);
                toolBar.Name = strBtnName;
                toolBar.Visible = true;
            }
        }

#endregion

#region 移动光标位置

// Go to a predefined bookmark, if the bookmark doesn't exists the application will raise an error
        public void GotoBookMark(string strBookMarkName)
        {
            // VB :  Selection.GoTo What:=wdGoToBookmark, Name:="nome"
            object Bookmark = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
            object NameBookMark = strBookMarkName;
            oWordApplic.Selection.GoTo(ref Bookmark, ref missing, ref missing, ref NameBookMark);
        }

public void GoToTheEnd()
        {
            // VB :  Selection.EndKey Unit:=wdStory
            object unit;
            unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            oWordApplic.Selection.EndKey(ref unit, ref missing);
        }

public void GoToLineEnd()
        {
            object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            object ext = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
            oWordApplic.Selection.EndKey(ref unit, ref ext);
        }

public void GoToTheBeginning()
        {
            // VB : Selection.HomeKey Unit:=wdStory
            object unit;
            unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
            oWordApplic.Selection.HomeKey(ref unit, ref missing);
        }

public void GoToTheTable(int ntable)
        {
            //    Selection.GoTo What:=wdGoToTable, Which:=wdGoToFirst, Count:=1, Name:=""
            //    Selection.Find.ClearFormatting
            //    With Selection.Find
            //        .Text = ""
            //        .Replacement.Text = ""
            //        .Forward = True
            //        .Wrap = wdFindContinue
            //        .Format = False
            //        .MatchCase = False
            //        .MatchWholeWord = False
            //        .MatchWildcards = False
            //        .MatchSoundsLike = False
            //        .MatchAllWordForms = False
            //    End With

object what;
            what = Microsoft.Office.Interop.Word.WdUnits.wdTable;
            object which;
            which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;
            object count;
            count = 1;
            oWordApplic.Selection.GoTo(ref what, ref which, ref count, ref missing);
            oWordApplic.Selection.Find.ClearFormatting();

oWordApplic.Selection.Text = "";
        }

public void GoToRightCell()
        {
            // Selection.MoveRight Unit:=wdCell
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
            oWordApplic.Selection.MoveRight(ref direction, ref missing, ref missing);
        }

public void GoToLeftCell()
        {
            // Selection.MoveRight Unit:=wdCell
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
            oWordApplic.Selection.MoveLeft(ref direction, ref missing, ref missing);
        }

public void GoToDownCell()
        {
            // Selection.MoveRight Unit:=wdCell
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            oWordApplic.Selection.MoveDown(ref direction, ref missing, ref missing);
        }

public void GoToUpCell()
        {
            // Selection.MoveRight Unit:=wdCell
            object direction;
            direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
            oWordApplic.Selection.MoveUp(ref direction, ref missing, ref missing);
        }

#endregion

#region 插入操作

public void InsertText(string strText)
        {
            oWordApplic.Selection.TypeText(strText);
        }

public void InsertLineBreak()
        {
            oWordApplic.Selection.TypeParagraph();
        }

/// <summary>
        /// 插入多个空行
        /// </summary>
        /// <param name="nline"></param>
        public void InsertLineBreak(int nline)
        {
            for (int i = 0; i < nline; i++)
                oWordApplic.Selection.TypeParagraph();
        }

public void InsertPagebreak()
        {
            // VB : Selection.InsertBreak Type:=wdPageBreak
            object pBreak = (int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
            oWordApplic.Selection.InsertBreak(ref pBreak);
        }

// 插入页码
        public void InsertPageNumber()
        {
            object wdFieldPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
            object preserveFormatting = true;
            oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range, ref wdFieldPage, ref missing, ref preserveFormatting);
        }

// 插入页码
        public void InsertPageNumber(string strAlign)
        {
            object wdFieldPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
            object preserveFormatting = true;
            oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range, ref wdFieldPage, ref missing, ref preserveFormatting);
            SetAlignment(strAlign);
        }

public void InsertImage(string strPicPath, float picWidth, float picHeight)
        {
            string FileName = strPicPath;
            object LinkToFile = false;
            object SaveWithDocument = true;
            object Anchor = oWordApplic.Selection.Range;
            oWordApplic.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor).Select();
            oWordApplic.Selection.InlineShapes[1].Width = picWidth; // 图片宽度 
            oWordApplic.Selection.InlineShapes[1].Height = picHeight; // 图片高度

// 将图片设置为四面环绕型 
            Microsoft.Office.Interop.Word.Shape s = oWordApplic.Selection.InlineShapes[1].ConvertToShape();
            s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
        }

public void InsertLine(float left, float top,

转C#操作Word辅助类(word2003)相关推荐

  1. C#操作Word辅助类(word2003)(转)

    /***************************************************************************  * word辅助类  * 作者:chengf ...

  2. java使用jacob操作word文档

    ava使用jacob操作word文档 java调用com组件操作word使用总结(jacob) 简单描述 在此处输入简单摘要 特别声明:使用java-com技术可以完成任何VBA可以完成的office ...

  3. poi操作word文档总结

    POI分段落生成纯Word动态模板并导入数据 导出数据,可以用word另存为xml格式的ftl文件,变量用${变量名}表示,然后在类中通过 freemarker去替换变量. 但是怎么导入word数据. ...

  4. 【MFC/C++操作word】Word篇(OLED/COM)

    原文链接:http://blog.csdn.net/xxxxxx91116/article/details/8543473 MFC操作Word 一.初始化操作 1.导入类库 下面的操作基于Word20 ...

  5. VC++ 操作 word

    摘要: 使用VC编程来操纵Office.你可以实现诸如:Word文件打印.传送数据到Word文档.发送E-MAIL.自动产生表格.Excel数据统计.圆饼图,直方图显示.自动报表生成.播放幻灯.doc ...

  6. c++ 操作Word

    摘要: 使用VC编程来操纵Office.你可以实现诸如:Word文件打印.传送数据到Word文档.发送E-MAIL.自动产生表格.Excel数据统计.圆饼图,直方图显示.自动报表生成.播放幻灯.doc ...

  7. VC++ 操作Word

    摘要: 使用VC编程来操纵Office.你可以实现诸如:Word文件打印.传送数据到Word文档.发送E-MAIL.自动产生表格.Excel数据统计.圆饼图,直方图显示.自动报表生成.播放幻灯.doc ...

  8. jacob操作word和excel

    jacob操作word和excel jacob的官方文档:http://danadler.com/jacob/ 微软的javasdk文档:http://f2.grp.yahoofs.com/v1/II ...

  9. java调用office接口_java调用com组件操作word使用总结(jacob)

    ava调用com组件操作word使用总结(jacob) 简单描述 在此处输入简单摘要 特别声明:使用java-com技术可以完成任何VBA可以完成的office文档操作; 一.准备工作 先了解一下概念 ...

最新文章

  1. 2.3.7 多生产者多消费者问题
  2. SQL查询存在一个表而不在另一个表中的数据
  3. 创建一个catkin工作空间
  4. Windows环境下配置php的curl扩展
  5. chrome 70 android,Android版Chrome Beta 70 (70.0.3538.17) 已发布
  6. go get报错:unrecognized import path “golang.org/x/net/context”…
  7. 为何手机可以用,电脑连接不上
  8. Facebook人工智能实验室的前世今生
  9. 机器视觉核心算法——图像预处理
  10. IE下载xlsx、docx、pptx文件时自动变成zip文件问题
  11. 【C语言应用】使用查表法计算CRC8
  12. 计算机网络电子邮件的格式,电子邮件的格式是什么
  13. 计算机点阵存储空间,计算机存储量计算存储400个24*24点阵汉字字形所需的存储容量是________....
  14. python调用foxmail 发邮件_foxmail 收取已发送邮件
  15. c语言模拟交通信号,C语言编写的交通信号灯
  16. 命令行编译工具NMAKE
  17. Android常用adb shell命令
  18. 盛迈坤电商:运营店铺需要怎么做
  19. python支持使用字典的键作为下标,Python 支持使用字典的“键”作为下标来访问字典中的值。...
  20. 网络学习 2g 3g 4g 技术对比 带宽理解 三大运营商手机网络模式 (制式)

热门文章

  1. vue项目实现单/多文件下载和打包压缩下载
  2. 原华为区块链科学家黄连金先生受邀担任Hashgard基金会战略顾问
  3. AutoCAD.NET API2018二次开发第十一章
  4. 2021寒假MISC打卡DAY2
  5. Java基础笔记_6_类和对象_成员变量
  6. ati备份 linux,恭喜自己 ati显卡驱动安装成功
  7. Linux内核系统论文写作虚拟机方案
  8. java解决异常_聊聊Java中的异常及处理
  9. Unity 获得时间戳
  10. 微信公众号支付测试方法