Aspose.Words使用教程之如何重命名合并字段

Aspose.Words For .NET是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。此外,API支持所有流行的Word处理文件格式,并允许将Word文档导出或转换为固定布局文件格式和最常用的图像/多媒体格式。
立即下载Aspose.Words最新版icon-default.png?t=M666http://www.evget.com/product/564

 一个示例展示如何创建自己的合并字段类,代表一个在微软的Word文档中允许您获取或设置它合并字段的名称。

Example

如何在一个文档里重命名字段。

C#

using System;
using System.Text;
using System.Text.RegularExpressions;
using Aspose.Words;
using Aspose.Words.Fields;

namespace Examples
{
/// <summary>
/// Shows how to rename merge fields in a Word document.
/// </summary>
public class ExRenameMergeFields : ExBase
{
/// <summary>
/// Finds all merge fields in a Word document and changes their names.
/// </summary>
public void RenameMergeFields()
{
// Specify your document name here.
Document doc = new Document(MyDir + "RenameMergeFields.doc");

// Select all field start nodes so we can find the merge fields.
NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
foreach (FieldStart fieldStart in fieldStarts)
{
if (fieldStart.FieldType.Equals(FieldType.FieldMergeField))
{
MergeField mergeField = new MergeField(fieldStart);
mergeField.Name = mergeField.Name + "_Renamed";
}
}

doc.Save(MyDir + "RenameMergeFields Out.doc");
}
}

/// <summary>
/// Represents a facade object for a merge field in a Microsoft Word document.
/// </summary>
internal class MergeField
{
internal MergeField(FieldStart fieldStart)
{
if (fieldStart.Equals(null))
throw new ArgumentNullException("fieldStart");
if (!fieldStart.FieldType.Equals(FieldType.FieldMergeField))
throw new ArgumentException("Field start type must be FieldMergeField.");

mFieldStart = fieldStart;

// Find the field separator node.
mFieldSeparator = fieldStart.GetField().Separator;
if (mFieldSeparator == null)
throw new InvalidOperationException("Cannot find field separator.");

mFieldEnd = fieldStart.GetField().End;
}

/// <summary>
/// Gets or sets the name of the merge field.
/// </summary>
internal string Name
{
get
{
return ((FieldStart)mFieldStart).GetField().Result.Replace("«", "").Replace("»", "");
}
set
{
// Merge field name is stored in the field result which is a Run
// node between field separator and field end.
Run fieldResult = (Run)mFieldSeparator.NextSibling;
fieldResult.Text = string.Format("«{0}»", value);

// But sometimes the field result can consist of more than one run, delete these runs.
RemoveSameParent(fieldResult.NextSibling, mFieldEnd);

UpdateFieldCode(value);
}
}

private void UpdateFieldCode(string fieldName)
{
// Field code is stored in a Run node between field start and field separator.
Run fieldCode = (Run)mFieldStart.NextSibling;

Match match = gRegex.Match(((FieldStart)mFieldStart).GetField().GetFieldCode());

string newFieldCode = string.Format(" {0}{1} ", match.Groups["start"].Value, fieldName);
fieldCode.Text = newFieldCode;

// But sometimes the field code can consist of more than one run, delete these runs.
RemoveSameParent(fieldCode.NextSibling, mFieldSeparator);
}

/// <summary>
/// Removes nodes from start up to but not including the end node.
/// Start and end are assumed to have the same parent.
/// </summary>
private static void RemoveSameParent(Node startNode, Node endNode)
{
if ((endNode != null) && (startNode.ParentNode != endNode.ParentNode))
throw new ArgumentException("Start and end nodes are expected to have the same parent.");

Node curChild = startNode;
while ((curChild != null) && (curChild != endNode))
{
Node nextChild = curChild.NextSibling;
curChild.Remove();
curChild = nextChild;
}
}

private readonly Node mFieldStart;
private readonly Node mFieldSeparator;
private readonly Node mFieldEnd;

private static readonly Regex gRegex = new Regex(@"\s*(?<start>MERGEFIELD\s|)(\s|)(?<name>\S+)\s+");
}
}

Visual Basic

Imports Microsoft.VisualBasic
Imports System
Imports System.Text
Imports System.Text.RegularExpressions
Imports Aspose.Words
Imports Aspose.Words.Fields

Namespace Examples
''' <summary>
''' Shows how to rename merge fields in a Word document.
''' </summary>
<TestFixture> _
Public Class ExRenameMergeFields
Inherits ExBase
''' <summary>
''' Finds all merge fields in a Word document and changes their names.
''' </summary>
<Test> _
Public Sub RenameMergeFields()
' Specify your document name here.
Dim doc As New Document(MyDir & "RenameMergeFields.doc")

' Select all field start nodes so we can find the merge fields.
Dim fieldStarts As NodeCollection = doc.GetChildNodes(NodeType.FieldStart, True)
For Each fieldStart As FieldStart In fieldStarts
If fieldStart.FieldType.Equals(FieldType.FieldMergeField) Then
Dim mergeField As New MergeField(fieldStart)
mergeField.Name = mergeField.Name & "_Renamed"
End If
Next fieldStart

doc.Save(MyDir & "RenameMergeFields Out.doc")
End Sub
End Class

''' <summary>
''' Represents a facade object for a merge field in a Microsoft Word document.
''' </summary>
Friend Class MergeField
Friend Sub New(fieldStart As FieldStart)
If fieldStart.Equals(Nothing) Then
Throw New ArgumentNullException("fieldStart")
End If
If Not fieldStart.FieldType.Equals(FieldType.FieldMergeField) Then
Throw New ArgumentException("Field start type must be FieldMergeField.")
End If

mFieldStart = fieldStart

' Find the field separator node.
mFieldSeparator = fieldStart.GetField().Separator
If mFieldSeparator Is Nothing Then
Throw New InvalidOperationException("Cannot find field separator.")
End If

mFieldEnd = fieldStart.GetField().End
End Sub

''' <summary>
''' Gets or sets the name of the merge field.
''' </summary>
Friend Property Name() As String
Get
Return DirectCast(mFieldStart, FieldStart).GetField().Result.Replace("«", "").Replace("»", "")
End Get
Set
' Merge field name is stored in the field result which is a Run
' node between field separator and field end.
Dim fieldResult As Run = DirectCast(mFieldSeparator.NextSibling, Run)
fieldResult.Text = String.Format("«{0}»", value)

' But sometimes the field result can consist of more than one run, delete these runs.
RemoveSameParent(fieldResult.NextSibling, mFieldEnd)

UpdateFieldCode(value)
End Set
End Property

Private Sub UpdateFieldCode(fieldName As String)

' Field code is stored in a Run node between field start and field separator.
Dim fieldCode As Run = DirectCast(mFieldStart.NextSibling, Run)

Dim match As Match = gRegex.Match(DirectCast(mFieldStart, FieldStart).GetField().GetFieldCode())

Dim newFieldCode As String = String.Format(" {0}{1} ", match.Groups("start").Value, fieldName)
fieldCode.Text = newFieldCode

' But sometimes the field code can consist of more than one run, delete these runs.
RemoveSameParent(fieldCode.NextSibling, mFieldSeparator)
End Sub

''' <summary>
''' Removes nodes from start up to but not including the end node.
''' Start and end are assumed to have the same parent.
''' </summary>
Private Shared Sub RemoveSameParent(startNode As Node, endNode As Node)
If (endNode IsNot Nothing) AndAlso (startNode.ParentNode <> endNode.ParentNode) Then
Throw New ArgumentException("Start and end nodes are expected to have the same parent.")
End If

Dim curChild As Node = startNode
While (curChild IsNot Nothing) AndAlso (curChild <> endNode)
Dim nextChild As Node = curChild.NextSibling
curChild.Remove()
curChild = nextChild
End While
End Sub

Private ReadOnly mFieldStart As Node
Private ReadOnly mFieldSeparator As Node
Private ReadOnly mFieldEnd As Node

Private Shared ReadOnly gRegex As New Regex("\s*(?<start>MERGEFIELD\s|)(\s|)(?<name>\S+)\s+")
End Class
End Namespace

Aspose全系产品已更新至最新版本,欢迎前往下载试用! 如需技术交流也可以私聊我哦~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值