Aspose.Words如何重命名合并字段 博客分类: 文档管理,控件,使用教程 Aspose.Words使用教程重命名
程序员文章站
2024-03-25 09:39:58
...
本文主要为介绍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