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

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

}
}

word 文档操作类,可以读出word中书签 批量替换内容,直接调用,布布扣,bubuko.com

时间: 2024-10-05 05:25:56

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

C#操作Word文档(加密、解密、对应书签插入分页符)

原文:C#操作Word文档(加密.解密.对应书签插入分页符) 最近做一个项目,客户要求对已经生成好的RTF文件中的内容进行分页显示,由于之前对这方面没有什么了解,后来在网上也找了相关的资料,并结合自己在MSDN上面的查找,后来总算把问题给解决掉啦.下面对C#操作Word文档(加密.解密.插入分页符)做一个简单的总结,希望对一些朋友有所帮忙吧.^_^ 写代码之前,需要引用对应的DLL文件: 1.Interop.Microsoft.Office.Interop.Word.dll  (网上可以下载)

C# Word文档操作——添加Word页眉、页脚和页码

在Word文档中,我们可以通过添加页眉.页脚的方式来丰富文档内容.添加页眉.页脚时,可以添加时间.日期.文档标题,文档引用信息.页码.内容解释.图片/LOGO等多种图文信息.同时也可根据需要调整文字或图片在页眉.页脚处的位置.因此,本文将介绍如何在C#中使用社区版控件Free Spire. Doc for .NET来添加页眉.页脚以及页码方法. 提示:下载安装该组件后注意在你的VS项目程序中引用dll文件(该dll文件可在安装文件下的Bin文件夹中获取) 一.添加文本.图片页眉 using Sp

C# 设置、删除、读取Word文档背景——基于Spire.Cloud.Word

Spire.Cloud.Word.Sdk提供了接口SetBackgroudColor().SetBackgroudImage().DeleteBackground().GetBackgroudColor()用于设置.删除及读取Word文档背景.本文将以C#程序为例演示如何来调用API接口实现以上内容操作. 必要步骤: 步骤一:dll文件获取及导入.通过官网下载SDK文件包. 下载后,解压文件,将Spire.Cloud.Word.Sdk.dll文件及其他三个dll添加引用至VS程序(如下图):或者

Word文档怎么翻译?翻译word文档简单步骤讲解

将文档进行翻译是我们经常遇到的事情,市面上也出现了很多翻译文档的工具,但是使用起来总觉得不是那么好用,一款易上手的工具对我们来说是非常重要的,今天的课堂就是小编给大家分享使用工具将word文档进行翻译的三个小技巧,一起来了解下吧! 文档翻译工具一:在线转换器 1.进入PDF在线转换器页面,在菜单栏中找到文档处理,在弹出的子栏目中找到word在线翻译: 2.通过点击选择文件将需要进行翻译的文件上传至指定区域即可,在自定义转换设置中可以根据自己的需要选择翻译的语种: 3.点击开始翻译,当进度条显示转

关于XML文档操作类

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Xml; 6 7 namespace ZW.ClassLibrary 8 { 9 public class XmlHelpers 10 { 11 /// <summary> 12 /// XML文档 13 /// </summary> 14 XmlDocument x

利用POI操作不同版本word文档中的图片以及创建word文档

我们都知道要想利用java对office操作最常用的技术就应该是POI了,在这里本人就不多说究竟POI是什么和怎么用了.先说本人遇到的问题,不同于利用POI去向word文档以及excel文档去写入数据和向外导出数据并且保存到数据库中这些类似的操作,由于业务上的需要需要利用POI去读取word中的图片,并且去把图片去保存为一个file文件.查了Apache公司提供的api帮助文档,再网友的一些线索,本人也总结了几中对不同word版本(.doc或者是.docx结尾)对于文件中所含图片的操作方式,希望

利用POI操作不同版本号word文档中的图片以及创建word文档

我们都知道要想利用java对office操作最经常使用的技术就应该是POI了,在这里本人就不多说到底POI是什么和怎么用了. 先说本人遇到的问题,不同于利用POI去向word文档以及excel文档去写入数据和向外导出数据而且保存到数据库中这些类似的操作,因为业务上的须要须要利用POI去读取word中的图片,而且去把图片去保存为一个file文件.查了Apache公司提供的api帮助文档,再网友的一些线索,本人也总结了几中对不同word版本号(.doc或者是.docx结尾)对于文件里所含图片的操作方

怎么把PDF转换成word文档编辑

很多办公类的文档都是用word编辑的,而现在很多场合都需要用到PDF文件,所以在发送文件时都会以PDF文件格式方式发送,如果接收到这种格式文件需要对文档内容进行编辑调整又或是需要运用到里面的一些内容信息,直接编辑还是有些麻烦的,但是可以把PDF文件转换成word文档,然后再对word文件编辑利用就简单多了. 想要将PDF转成word得使文件内容没有大的变动,最好和原PDF文件保存一致,直接复制粘贴的方法是不行的,需要直接转换文档的格式.如果文档有编辑限制或者是加密的,则需要先去除这些限制. 转换

基于C#.NET的动态Word文档生成及数据填充研究

利用C#.NET设计的管理信息系统应用非常广泛,但其报表往往是利用水晶报表或其它工具形成固定式报表,这样不便于修改和电子文档的保存及传递,如果能将输出结果写入到Word文档中这样就解决了这个问题.现从以下几个方面介绍如何利用C#.NET来控制Word文档的操作.1 利用C#.NET生成和设置Word文档我们用VS2008中的C#.NET来实现的,所以要安装好VS2008.在编程之前必须从“项目”菜单上“添加引用”对话框的“COM”选硕卡中添加对类型库的引用,并在程序首部加入“usingWord;