本文主要为介绍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
相关推荐
- `Field`类:用于处理Word文档中的字段,如占位符或合并字段。`Document.GetFirstField()`可以获取文档中的第一个字段,然后可以进行操作或替换。 - `MailMergeDataSource`类:用于提供数据源,可以是从数据库、...
4. **XML数据源和邮件合并**:Aspose.Words的邮件合并功能可以结合XML数据源,动态生成批量的个性化文档。开发者可以指定XML文件中的元素与Word模板中的字段进行匹配,实现大规模的文档生成。 5. **XML样式和元素...
Aspose.Words是一款强大的文档处理库,主要用于在.NET环境中创建、编辑、转换和显示Microsoft Word文档。这个官方例子程序提供了大量的示例代码,帮助开发者更好地理解和应用Aspose.Words的功能。 1. **Aspose....
利用Aspose.Words,开发者可以轻松地创建、编辑、格式化文档,插入图片、图表、页眉和页脚,应用邮件合并,执行复杂的文本替换操作,并且能够将Word文档转换为PDF、HTML、EPUB等格式。它还具有高度的兼容性,确保在...
4. **自定义Mail Merge行为**:Aspose.Words提供了许多高级选项来控制Mail Merge的行为,如条件字段、多表合并、域事件处理等。例如,你可以使用`MailMerge.OnBeforeMerge`事件来在合并前处理特定记录。 5. **处理...
Aspose.Words for .NET是一款强大的文档处理库,专为.NET开发者设计,它允许程序员在不依赖Microsoft Office的情况下创建、编辑、转换和打印Word文档。这个库提供了丰富的API,能够处理复杂的格式化、布局、图像处理...
4. **邮件合并**:Aspose.Word支持邮件合并,能够将数据源(如CSV、Excel或数据库)与Word文档模板结合,批量生成个性化文档。 5. **文档比较**:该库提供了比较两个Word文档的功能,可以识别并突出显示两者之间的...
2. 邮件合并字段:在模板中定义邮件合并字段,通过Execute方法执行合并过程。 八、宏和VBA支持 虽然Aspose.Words主要处理文档内容,但也可以读取和保存Word文档中的宏和VBA项目,这对于某些特定的应用场景非常有用...
Aspose.Words是一款强大的文档处理库,主要用于在.NET环境中创建、编辑和操作Microsoft Word文档。17.7版本是该库的一个更新迭代,提供无水印版本,意味着它不包含任何开发者或试用版的标识水印,适合于学习和非商业...
此外,Aspose.Words还可以进行模板填充、邮件合并,以及文档比较和修订。 5. **Aspose.Total**:这是Aspose所有组件的集合,提供了一站式的文档处理解决方案。包含Aspose.Cells、Aspose.Pdf、Aspose.Slides和Aspose...
### Aspose.Words 控件操作示例—导出Word文档 #### Aspose.Words 控件简介 Aspose.Words 是一款非可视化的.NET类库,主要用于操作Word文档。这款类库的强大之处在于它无需依赖Microsoft Office环境即可实现对Word...
此外,它还支持高级功能,如条件文本、邮件合并、宏和VBA支持,以及复杂的表单字段处理。 Aspose.Words的优势在于其广泛的支持和丰富的功能集,不仅限于转换,还包括文档的创建、编辑、比较、审阅和保护等。这使得...
Aspose.Words 是一个强大的.NET库,专门用于处理Microsoft Word文档。这个无水印可发布版本,"aspose.words21.4 for .NET",是专为开发者设计的,旨在帮助他们集成到自己的应用程序中,进行各种Word文档的操作,而...
1. **Aspose.Words**: 这个DLL文件是Aspose针对Microsoft Word文档处理的库。它允许开发者在没有安装Microsoft Office的情况下创建、编辑、转换和操作DOC、DOCX、ODT等格式的文档。你可以利用Aspose.Words进行文本...
Aspose.Words-readme.txt 提供了关于Aspose.Words组件的信息。这是一个强大的文本处理库,允许开发者在.NET环境中创建、编辑、转换和操作Microsoft Word文档。它支持多种格式,如DOC、DOCX、ODT、RTF等,还能够进行...
《Aspose.Words for Java 16:高效文档处理的利器》 Aspose.Words for Java 是一个强大的文档处理库,专为Java开发者设计,它允许程序员在Java应用程序中创建、编辑、转换和呈现各种文档格式,如DOC、DOCX、PDF、...
- **合并字段**:利用邮件合并功能,将数据源与Word模板结合,批量生成个性化文档。 - **宏支持**:处理包含VBA宏的文档,虽然Aspose.Words不执行宏,但能读写宏代码。 3. **图像和图表** - **插入和操作图像**...
压缩包内的aspose.word.dll是外部引用,还有两个数据连接驱动。主要解决开发过程中b/s,c/s下的将数据库中多条信息按word模版导出的问题。 模版文件在相应的运行文件目录内。模版中的域名称同数据库中的字段名相同...
Aspose.Words是一个著名的Java库,它允许开发者在没有安装Microsoft Word的情况下,处理Word文档的各种操作,如创建、编辑、转换、打印等。这个资源达人分享的"aspose-words-15.8.0.zip"是Aspose.Words的一个版本,...