文檔金喜正規(guī)買(mǎi)球>>E-iceblue中文文檔>>在 Word 文檔中添加、計(jì)數(shù)、檢索和刪除變量
在 Word 文檔中添加、計(jì)數(shù)、檢索和刪除變量
文檔變量用于在宏會(huì)話之間保留宏設(shè)置。Spire.Doc 允許添加變量、計(jì)算變量的數(shù)量、檢索變量的名稱(chēng)和值以及刪除 Word 文檔中的特定變量。
添加變量
使用 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(); } } }
計(jì)算變量的數(shù)量
使用 Count 屬性返回文檔中的變量數(shù)。
//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);
檢索變量的名稱(chēng)和值
使用 GetNameByIndex 和 GetValueByIndex 方法按索引檢索變量的名稱(chēng)和值,并使用 Variables[String Name] 按名稱(chēng)檢索或設(shè)置變量的值。
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); } } }
歡迎下載|體驗(yàn)更多E-iceblue產(chǎn)品
如需獲取更多產(chǎn)品相關(guān)信息請(qǐng)咨詢(xún)