Word控件Spire.Doc 【文档操作】教程(十四):使用 C# 在 Word 文档中添加、计数、检索和删除变量

文档变量用于在宏会话之间保留宏设置。Spire.Doc 允许添加变量、计算变量的数量、检索变量的名称和值以及删除 Word 文档中的特定变量。
Spire.Doc for.NET 最新下载 

欢迎下载|体验更多E-iceblue产品 技术交流Q群(767755948)   

添加变量

使用 Add 方法将变量添加到文档中。以下示例将名为“A1”的文档变量添加到文档中,值为 12。

using Spire.Doc;
using Spire.Doc.Documents;
namespace ADDVARIABLE
{
class Program
{

static void Main(string[] args)
{
//Instantiate a document object
Document document = new Document();
//Add a section
Section section = document.AddSection();
//Add a paragraph
Paragraph paragraph = section.AddParagraph();
//Add a DocVariable Filed
paragraph.AppendField("A1", FieldType.FieldDocVariable);
//Add a document variable to the DocVariable Filed
document.Variables.Add("A1", "12");
//Update fields
document.IsUpdateFields = true;
//Save and close the document object
document.SaveToFile("AddVariable.docx", FileFormat.Docx2013);
document.Close();
}
}
}

计算变量的数量

使用 Count 属性返回文档中的变量数。

//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;

Console.WriteLine(number);

检索变量的名称和值

使用 GetNameByIndex 和 GetValueByIndex 方法按索引检索变量的名称和值,并使用 Variables[String Name] 按名称检索或设置变量的值。

using Spire.Doc;
using Spire.Doc.Documents;
using System;
namespace COUNTVARIABLE
{

class Program
{

static void Main(string[] args)
{
//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;

Console.WriteLine(number);

}
}
}

删除特定变量

使用 Remove 方法从文档中删除变量。
using Spire.Doc;
using System;
namespace RETRIEVEVARIABLE
{
class Program
{
static void Main(string[] args)
{
//Load the document
Document document = new Document("AddVariable.docx");

// Retrieve name of the variable by index
string s1 = document.Variables.GetNameByIndex(0);

// Retrieve value of the variable by index
string s2 = document.Variables.GetValueByIndex(0);

// Retrieve or set value of the variable by name
string s3 = document.Variables["A1"];

Console.WriteLine("{0} {1} {2}", s1, s2, s3);
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值