using System;
using System.Collections.Generic;
using System.Text;
using Word = Microsoft.Office.Interop.Word;

namespace ELO.BLL
{
/*
* Description:用于Word基本操作类
*/
public partial class Helper_Word
{
#region 私有成员

private Word.ApplicationClass _wordApplication;
private Word.Document _wordDocument;
object missing = System.Reflection.Missing.Value;

#endregion

#region 公开属性

/// <summary>
/// ApplciationClass
/// </summary>
public Word.ApplicationClass WordApplication
{
get
{
return _wordApplication;
}
}

/// <summary>
/// Document
/// </summary>
public Word.Document WordDocument
{
get
{
return _wordDocument;
}
}

#endregion

#region 构造函数

public Helper_Word()
{
_wordApplication = new Word.ApplicationClass();
}
public Helper_Word(Word.ApplicationClass wordApplication)
{
_wordApplication = wordApplication;
}

#endregion

#region 基本操作(新建、打开、保存、关闭)

/// <summary>
/// 新建并打开一个文档(默认缺省值)
/// </summary>
public void CreateAndActive()
{
_wordDocument = CreateOneDocument(missing, missing, missing, missing);
_wordDocument.Activate();
}

/// <summary>
/// 打开指定文件
/// </summary>
/// <param name="FileName">文件名(包含路径)</param>
/// <param name="IsReadOnly">打开后是否只读</param>
/// <param name="IsVisibleWin">打开后是否可视</param>
/// <returns>打开是否成功</returns>
public bool OpenAndActive(string FileName, bool IsReadOnly, bool IsVisibleWin)
{
if (string.IsNullOrEmpty(FileName))
{
return false;
}
try
{
_wordDocument = OpenOneDocument(FileName, missing, IsReadOnly, missing, missing, missing, missing, missing, missing, missing, missing, IsVisibleWin, missing, missing, missing, missing);
_wordDocument.Activate();
return true;
}
catch
{
return false;
}
}

/// <summary>
/// 关闭
/// Closes the specified document or documents.
/// </summary>
public void Close()
{
if (_wordDocument != null)
{
_wordDocument.Close(ref missing, ref missing, ref missing);
_wordApplication.Application.Quit(ref missing, ref missing, ref missing);
}
}

/// <summary>
/// 保存
/// </summary>
public void Save()
{
if (_wordDocument == null)
{
_wordDocument = _wordApplication.ActiveDocument;
}
_wordDocument.Save();
}

/// <summary>
/// 保存为...
/// </summary>
/// <param name="FileName">文件名(包含路径)</param>
public void SaveAs(string FileName)
{
if (_wordDocument == null)
{
_wordDocument = _wordApplication.ActiveDocument;
}
object objFileName = FileName;

_wordDocument.SaveAs(ref objFileName, 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);
}

/// <summary>
/// 新建一个Document
/// </summary>
/// <param name="template">Optional Object. The name of the template to be used for the new document. If this argument is omitted, the Normal template is used.</param>
/// <param name="newTemplate">Optional Object. True to open the document as a template. The default value is False.</param>
/// <param name="documentType">Optional Object. Can be one of the following WdNewDocumentType constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or wdNewWebPage. The default constant is wdNewBlankDocument.</param>
/// <param name="visible">Optional Object. True to open the document in a visible window. If this value is False, Microsoft Word opens the document but sets the Visible property of the document window to False. The default value is True.</param>
public Word.Document CreateOneDocument(object template, object newTemplate, object documentType, object visible)
{
return _wordApplication.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
}

/// <summary>
/// 打开一个已有文档
/// </summary>
/// <param name="FileName"></param>
/// <param name="ConfirmConversions"></param>
/// <param name="ReadOnly"></param>
/// <param name="AddToRecentFiles"></param>
/// <param name="PasswordDocument"></param>
/// <param name="PasswordTemplate"></param>
/// <param name="Revert"></param>
/// <param name="WritePasswordDocument"></param>
/// <param name="WritePasswordTemplate"></param>
/// <param name="Format"></param>
/// <param name="Encoding"></param>
/// <param name="Visible"></param>
/// <param name="OpenAndRepair"></param>
/// <param name="DocumentDirection"></param>
/// <param name="NoEncodingDialog"></param>
/// <param name="XMLTransform"></param>
/// <returns></returns>
public Word.Document OpenOneDocument(object FileName, object ConfirmConversions, object ReadOnly,
object AddToRecentFiles, object PasswordDocument, object PasswordTemplate, object Revert,
object WritePasswordDocument, object WritePasswordTemplate, object Format, object Encoding,
object Visible, object OpenAndRepair, object DocumentDirection, object NoEncodingDialog, object XMLTransform)
{
try
{
return _wordApplication.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);
}
catch
{
return null;
}
}

#endregion

#region 移动光标位置

/// <summary>
/// 光标移动到指定书签位置,书签不存在时不移动
/// </summary>
/// <param name="bookMarkName"></param>
/// <returns></returns>
public bool GoToBookMark(string bookMarkName)
{
//是否存在书签
if (_wordDocument.Bookmarks.Exists(bookMarkName))
{
object what = Word.WdGoToItem.wdGoToBookmark;
object name = bookMarkName;
GoTo(what, missing, missing, name);
return true;
}
return false;
}

/// <summary>
/// 移动光标
/// Moves the insertion point to the character position immediately preceding the specified item.
/// </summary>
/// <param name="what">Optional Object. The kind of item to which the selection is moved. Can be one of the WdGoToItem constants.</param>
/// <param name="which">Optional Object. The item to which the selection is moved. Can be one of the WdGoToDirection constants. </param>
/// <param name="count">Optional Object. The number of the item in the document. The default value is 1.</param>
/// <param name="name">Optional Object. If the What argument is wdGoToBookmark, wdGoToComment, wdGoToField, or wdGoToObject, this argument specifies a name.</param>
public void GoTo(object what, object which, object count, object name)
{
_wordApplication.Selection.GoTo(ref what, ref which, ref count, ref name);
}

/// <summary>
/// 向右移动一个字符
/// </summary>
public void MoveRight()
{
MoveRight(1);
}

/// <summary>
/// 向右移动N个字符
/// </summary>
/// <param name="num"></param>
public void MoveRight(int num)
{
object unit = Word.WdUnits.wdCharacter;
object count = num;
MoveRight(unit, count, missing);
}

/// <summary>
/// 向下移动一个字符
/// </summary>
public void MoveDown()
{
MoveDown(1);
}

/// <summary>
/// 向下移动N个字符
/// </summary>
/// <param name="num"></param>
public void MoveDown(int num)
{
object unit = Word.WdUnits.wdCharacter;
object count = num;
MoveDown(unit, count, missing);
}
/// <summary>
/// 光标上移
/// Moves the selection up and returns the number of units it's been moved.
/// </summary>
/// <param name="unit">Optional Object. The unit by which to move the selection. Can be one of the following WdUnits constants: wdLine, wdParagraph, wdWindow or wdScreen etc. The default value is wdLine.</param>
/// <param name="count">Optional Object. The number of units the selection is to be moved. The default value is 1.</param>
/// <param name="extend">Optional Object. Can be either wdMove or wdExtend. If wdMove is used, the selection is collapsed to the end point and moved up. If wdExtend is used, the selection is extended up. The default value is wdMove.</param>
/// <returns></returns>
public int MoveUp(object unit, object count, object extend)
{
return _wordApplication.Selection.MoveUp(ref unit, ref count, ref extend);
}

/// <summary>
/// 光标下移
/// Moves the selection down and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public int MoveDown(object unit, object count, object extend)
{
return _wordApplication.Selection.MoveDown(ref unit, ref count, ref extend);
}

/// <summary>
/// 光标左移
/// Moves the selection to the left and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public int MoveLeft(object unit, object count, object extend)
{
return _wordApplication.Selection.MoveLeft(ref unit, ref count, ref extend);
}

/// <summary>
/// 光标右移
/// Moves the selection to the left and returns the number of units it's been moved.
/// 参数说明详见MoveUp
/// </summary>
public int MoveRight(object unit, object count, object extend)
{
return _wordApplication.Selection.MoveRight(ref unit, ref count, ref extend);
}

#endregion

#region 查找、替换

/// <summary>
/// 替换书签内容
/// </summary>
/// <param name="bookMarkName">书签名</param>
/// <param name="text">替换后的内容</param>
public void ReplaceBookMark(string bookMarkName, string text)
{
bool isExist = GoToBookMark(bookMarkName);
if (isExist)
{
InsertText(text);
}
}

/// <summary>
/// 替换
/// </summary>
/// <param name="oldText">待替换的文本</param>
/// <param name="newText">替换后的文本</param>
/// <param name="replaceType">All:替换所有、None:不替换、FirstOne:替换第一个</param>
/// <param name="isCaseSensitive">大小写是否敏感</param>
/// <returns></returns>
public bool Replace(string oldText, string newText, string replaceType, bool isCaseSensitive)
{
if (_wordDocument == null)
{
_wordDocument = _wordApplication.ActiveDocument;

}
object findText = oldText;
object replaceWith = newText;
object wdReplace;
object matchCase = isCaseSensitive;
switch (replaceType)
{
case "All":
wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
break;
case "None":
wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone;
break;
case "FirstOne":
wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
break;
default:
wdReplace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
break;
}
_wordDocument.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置

return _wordDocument.Content.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
ref wdReplace, ref missing, ref missing, ref missing, ref missing);
}

#endregion

#region 插入、删除操作

/// <summary>
/// 插入文本 Inserts the specified text.
/// </summary>
/// <param name="text"></param>
public void InsertText(string text)
{
_wordApplication.Selection.TypeText(text);
}

/// <summary>
/// Enter(换行) Inserts a new, blank paragraph.
/// </summary>
public void InsertLineBreak()
{
_wordApplication.Selection.TypeParagraph();
}
/// <summary>
/// 插入图片(图片大小自适应)
/// </summary>
/// <param name="fileName">图片名(包含路径)</param>
public void InsertPic(string fileName)
{
object range = _wordApplication.Selection.Range;
InsertPic(fileName, missing, missing, range);
}

/// <summary>
/// 插入图片
/// </summary>
/// <param name="fileName">图片名(包含路径)</param>
/// <param name="width">设置宽度</param>
/// <param name="height">设置高度</param>
public void InsertPic(string fileName, float width, float height)
{
object range = _wordApplication.Selection.Range;
InsertPic(fileName, missing, missing, range, width, height);
}

/// <summary>
/// 插入图片(带标题)
/// </summary>
/// <param name="fileName">图片名(包含路径)</param>
/// <param name="width">设置宽度</param>
/// <param name="height">设置高度<</param>
/// <param name="caption">标题或备注文字</param>
public void InsertPic(string fileName, float width, float height, string caption)
{
object range = _wordApplication.Selection.Range;
InsertPic(fileName, missing, missing, range, width, height, caption);
}

/// <summary>
/// 插入图片(带标题)
/// </summary>
public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height, string caption)
{
_wordApplication.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();
if (Width > 0)
{
_wordApplication.Selection.InlineShapes[1].Width = Width;
}
if (Height > 0)
{
_wordApplication.Selection.InlineShapes[1].Height = Height;
}

object Label = Word.WdCaptionLabelID.wdCaptionFigure;
object Title = caption;
object TitleAutoText = "";
object Position = Word.WdCaptionPosition.wdCaptionPositionBelow;
object ExcludeLabel = true;
_wordApplication.Selection.InsertCaption(ref Label, ref Title, ref TitleAutoText, ref Position, ref ExcludeLabel);
MoveRight();
}

/// <summary>
/// Adds a picture to a document.
/// </summary>
/// <param name="FileName">Required String. The path and file name of the picture.</param>
/// <param name="LinkToFile">Optional Object. True to link the picture to the file from which it was created. False to make the picture an independent copy of the file. The default value is False.</param>
/// <param name="SaveWithDocument">Optional Object. True to save the linked picture with the document. The default value is False.</param>
/// <param name="Range">Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically.</param>
/// <param name="Width">Sets the width of the specified object, in points. </param>
/// <param name="Height">Sets the height of the specified inline shape. </param>
public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height)
{
_wordApplication.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();
_wordApplication.Selection.InlineShapes[1].Width = Width;
_wordApplication.Selection.InlineShapes[1].Height = Height;
MoveRight();
}

/// <summary>
/// Adds a picture to a document.
/// </summary>
/// <param name="FileName">Required String. The path and file name of the picture.</param>
/// <param name="LinkToFile">Optional Object. True to link the picture to the file from which it was created. False to make the picture an independent copy of the file. The default value is False.</param>
/// <param name="SaveWithDocument">Optional Object. True to save the linked picture with the document. The default value is False.</param>
/// <param name="Range">Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically.</param>
public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range)
{
_wordApplication.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range);
}

/// <summary>
/// 插入书签
/// 如过存在同名书签,则先删除再插入
/// </summary>
/// <param name="bookMarkName">书签名</param>
public void InsertBookMark(string bookMarkName)
{
存在则先删除
//if (_wordDocument.Bookmarks.Exists(bookMarkName))
//{
// DeleteBookMark(bookMarkName);
//}
object range = _wordApplication.Selection.Range;
_wordDocument.Bookmarks.Add(bookMarkName, ref range);

}

/ <summary>
/ 删除书签
/ </summary>
/ <param name="bookMarkName">书签名</param>
//public void DeleteBookMark(string bookMarkName)
//{
// if (_wordDocument.Bookmarks.Exists(bookMarkName))
// {
// WordDocument bookMarks = _wordDocument.Bookmarks;
// for (int i = 1; i <= bookMarks.Count; i++)
// {
// object index = i;
// object bookMark = bookMarks.get_Item(ref index);
// if (bookMark.Name == bookMarkName)
// {
// bookMark.Delete();
// break;
// }
// }
// }
//}

/ <summary>
/ 删除所有书签
/ </summary>
//public void DeleteAllBookMark()
//{
// for (; _wordDocument.Bookmarks.Count > 0; )
// {
// object index = _wordDocument.Bookmarks.Count;
// object bookmark = _wordDocument.Bookmarks.get_Item(ref index);
// bookmark.Delete();
// }
//}
#endregion

}
}

转载于:https://www.cnblogs.com/luyiwei/p/3750228.html

word 文档操作类,可以读出word中书签 批量替换内容,直接调用相关推荐

  1. XWPF POI word文档操作

    运用Poi的XWPF操作word文档 Word文档基础知识的简介 word文档包括 页眉.页脚.脚注.批注.链接.正文部分,在XWPF中都有与之对应的类: .docx文件的文档的根 XWPFDocum ...

  2. java access ole word,利用OLE对象实现Word文档操作

    Word 是常用的字处理软件,在编程中充分利用现有的Word 文档就可以减少很多数据的处理.详细介绍了在ASP.NET 的程序中,利用数据库中的OLE 对象,实现Word文档的在线存取及预览. 1.引 ...

  3. Qt对word文档操作总结

    Qt对word文档操作总结 近期在使用Qt对word进行读写操作时候遇到很多问题,对于Qt内部没有很好的库函数可以使用.office官网上的文档只有VBA的示例,没有Qt的语法例子.在这里作者介绍了一 ...

  4. C++实例(十)Word文档操作

    Word文档操作 一.Word文档的基本操作 打开Word文档 在开发应用程序时,有时需要调用Word文档,如果让用户在磁盘中寻找文档将会很麻烦. 读取Word文档文本内容 在使用程序控制Word文档 ...

  5. html中只能上传文件word,HTML文件表单,接受Word文档(HTML file form, accept Word documents)...

    HTML文件表单,接受Word文档(HTML file form, accept Word documents) 我在这里遇到了一个奇怪的问题. (不管怎样,或者我只是忽略了一些非常简单的东西.) 我 ...

  6. Word文档怎么删除html标签,word怎么清除所有格式

    在 Word 中,选择性粘贴有三种格式 分别为保留原格式.合并格式和保留原文本,另外,还可以选择"HTML 格式.无格式文本.无格式的 Unicode 文本.带格式文本(RTF)和图片(增强 ...

  7. word怎么显示计算机数字,如何使word文档自动显示字数统计 Word自动统计文档字数在哪里...

    如何使word文档自动显示字数统计 Word自动统计文档字数在哪里 Word中有一个非常实用的字数统计功能,如要统计一个文档中的字数,直接在菜单栏中单击"审阅→字数统计",便可得到 ...

  8. wps的ppt怎么存html,如何将网页快速转换为WPS与WORD文档 ppt怎么转换成word文档

    导读:小编根据大家的需要整理了一份关于<如何将网页快速转换为WPS与WORD文档 ppt怎么转换成word文档>的内容,具体内容: 看到图文并茂的网页,想把它全部或部分转换为WPS或者WO ...

  9. word计算机桌面加密,word文档加密,怎么让word自动加密 -电脑资料

    Word提供了加密的功能,但不能自动给文档加密, 第一步:在"工具"菜单中选择"宏"选项卡,单击"宏"命令,键入宏的名称"AllA ...

最新文章

  1. 关于java继承中父类方法可见性探讨
  2. C# - 委托中的逆变
  3. Spring Boot导出jar包发布
  4. 人人网SDK Demo项目学习获取系统Log类
  5. relative与absolute相结合
  6. Linux内核分析 - 网络[八补]:IP协议补充
  7. 基于OpenCV的计算机视觉入门(3)图像特效
  8. 国务院《政务信息资源共享管理暂行办法》带来哪些新商机?
  9. Matlab2017b配置C++/C/Fortan编译器的问题
  10. 前端存储之websql
  11. Grasshopper GHPython 报错: Solution exception:找不到方法: “Void Microsoft.Scripting.Utils
  12. 【单片机基础篇】51单片机流水灯原理
  13. python word文档合并_[Python 学习笔记]用Python进行docx文档合并
  14. 北京建筑大学计算机学院岑孝鹏,北京建筑大学
  15. matplotlib 网格线不要覆盖柱状图
  16. AQS——CLH队列维护方法详解
  17. scp 是我小看了你---基于密钥传输!
  18. 你离解决windows开机无法使用PIN登陆就差一步
  19. 【poj 1182】食物链 并查集应用
  20. Linux磁盘扩展(非LVM+LVM)

热门文章

  1. JS Event事件
  2. ZeroMQ接口函数之 :zmq - 0MQ 轻量级消息传输内核
  3. 科技领袖技术大亨们被指是现代强盗:不仅赚钱还想垄断
  4. Widget创建过程(将RemoteViews发给WidgetHost)
  5. Java中几种日期格式相互转换
  6. 做程序开发的你如果经常用Redis,这些问题肯定会遇到
  7. 为RecyclerView添加下拉刷新(PullToRefresh)功能
  8. electron/nodejs实现调用golang函数
  9. 取出DataTime的年,月,日,时,分
  10. redis在windows10上跑起来