• 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
    {
    /// 
    /// Shows how to rename merge fields in a Word document.
    /// 
    public class ExRenameMergeFields : ExBase
    {
    /// 
    /// Finds all merge fields in a Word document and changes their names.
    /// 
    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");
    }
    }
    
    /// 
    /// Represents a facade object for a merge field in a Microsoft Word document.
    /// 
    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;
    }
    
    /// 
    /// Gets or sets the name of the merge field.
    /// 
    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);
    }
    
    /// 
    /// Removes nodes from start up to but not including the end node.
    /// Start and end are assumed to have the same parent.
    /// 
    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*(?MERGEFIELD\s|)(\s|)(?\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
    ''' 
    ''' Shows how to rename merge fields in a Word document.
    ''' 
     _
    Public Class ExRenameMergeFields
    Inherits ExBase
    ''' 
    ''' Finds all merge fields in a Word document and changes their names.
    ''' 
     _
    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
    
    ''' 
    ''' Represents a facade object for a merge field in a Microsoft Word document.
    ''' 
    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
    
    ''' 
    ''' Gets or sets the name of the merge field.
    ''' 
    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
    
    ''' 
    ''' Removes nodes from start up to but not including the end node.
    ''' Start and end are assumed to have the same parent.
    ''' 
    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*(?MERGEFIELD\s|)(\s|)(?\S+)\s+")
    End Class
    End Namespace

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

  • 相关阅读:
    docker常用命令二
    Django中djangorestframework-simplejwt的使用
    【桌面开发】vscode+Debugger-For-NWjs+nwjs-sdk-vx.x.x-xxos调试环境搭建
    进程互斥的硬件实现方法
    代理模式(Proxy Pattern)
    2.5 晶体管单管放大电路的三种基本接法
    css样式
    Zabbix自动监控windows端口(主动监控方式)
    【PAT甲级】1028 List Sorting
    电脑文件如何自动备份到网盘里?
  • 原文地址:https://blog.csdn.net/m0_67129275/article/details/126401720