文档变量用于在宏会话之间保留宏设置。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);
}
}
}