文档变量用于在宏会话之间保留宏设置。Spire.Doc 允许添加变量、计算变量的数量、检索变量的名称和值以及删除 Word 文档中的特定变量。
添加变量
使用 Add 方法将变量添加到文档中。以下示例将名为“A1”的文档变量添加到文档中,值为 12。
using Spire.Doc;using Spire.Doc.Documents;namespace ADDVARIABLE{class Program{static void Main(string[] args){//Instantiate a document objectDocument document = new Document();//Add a sectionSection section = document.AddSection();//Add a paragraphParagraph paragraph = section.AddParagraph();//Add a DocVariable Filedparagraph.AppendField("A1", FieldType.FieldDocVariable);//Add a document variable to the DocVariable Fileddocument.Variables.Add("A1", "12");//Update fieldsdocument.IsUpdateFields = true;//Save and close the document objectdocument.SaveToFile("AddVariable.docx", FileFormat.Docx2013);document.Close();}}}

计算变量的数量
使用 Count 属性返回文档中的变量数。
//Load the documentDocument document = new Document("AddVariable.docx");//Get the number of variables in the documentint 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 documentDocument document = new Document("AddVariable.docx");//Get the number of variables in the documentint number = document.Variables.Count;Console.WriteLine(number);}}}

删除特定变量
使用 Remove 方法从文档中删除变量。using Spire.Doc;using System;namespace RETRIEVEVARIABLE{class Program{static void Main(string[] args){//Load the documentDocument document = new Document("AddVariable.docx");// Retrieve name of the variable by indexstring s1 = document.Variables.GetNameByIndex(0);// Retrieve value of the variable by indexstring s2 = document.Variables.GetValueByIndex(0);// Retrieve or set value of the variable by namestring s3 = document.Variables["A1"];Console.WriteLine("{0} {1} {2}", s1, s2, s3);}}}
欢迎下载|体验更多E-iceblue产品
如需获取更多产品相关信息请咨询在线客服

标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!