Aspose.Words如何重命名合并字段

       本文主要为介绍Aspose.Words使用教程——重命名合并字段。

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

Example

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

 

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+");
}
}

 

 

 

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值