本分步教程将指导您如何使用 C# 在 Word 中插入超链接。它提供了插入普通文本的完整步骤以及仅在几行代码的帮助下指向 URL 的超链接。它有助于使用 C# 在 Word 中添加超链接,以便可以完全控制自定义超链接文本并将输出文件保存为 DOC 或 DOCX 文件。
使用 C# 在 Word 中插入链接的步骤
- 搭建开发环境使用Aspose.Words for .NET添加超链接
- 使用 Document 类创建一个新文件并使用 DocumentBuilder 对象放置一些文本
- 设置插入超链接文本的格式
- 插入超链接、目标 URL 和 URL 的标志
- 清除格式并再次添加一些普通文本
- 保存其中包含超链接的 Word 文件
这些步骤总结了如何使用 C# 在 Word 中添加链接的过程。它包含创建 Word 文件、使用 DocumentBuilder 类在其中插入普通文本、然后设置格式以将一些文本作为超链接插入并链接到 URL 的详细步骤。添加超链接后,格式将被清除,然后再次将普通文本添加到 Word 文件,然后再将其保存到磁盘上。
使用 C# 在 Word 中插入超链接的代码
using System.Drawing; | |
using Aspose.Words; | |
namespace AsposeProjects | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to add hyperlink in MS Word file using C# | |
{ | |
// Set license | |
License lic = new License(); | |
lic.SetLicense("Aspose.Total.lic"); | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.Write("Please make sure to visit "); | |
// Specify font formatting for the hyperlink. | |
builder.Font.Color = Color.Blue; | |
builder.Font.Underline = Underline.Single; | |
// Insert the link. | |
builder.InsertHyperlink("Aspose Website", "https://www.aspose.com", false); | |
// Revert to default formatting. | |
builder.Font.ClearFormatting(); | |
builder.Write(" for more information."); | |
doc.Save("Insert_Hyperlink_In_Document.doc"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
此代码演示使用 C# 添加到 Word 文档的超链接,其中 DocumentBuilder 类对象用于插入普通文本以及超链接形式的格式化文本。一旦更改字体颜色和其他属性等格式,添加到文档中的所有文本都将采用相同的格式。最后,在使用 InsertHyperlink() 方法添加超链接后,如果需要,将调用 Font 类中的 ClearFormatting() 方法在文档中再次插入普通文本。
本文教会了我们如何使用 C# 在 Word 中添加超链接。如果您想了解添加书签的过程,请参阅 如何使用C#在Word中添加书签 上的文章。