文檔金喜正規(guī)買球>>Spire.Doc系列教程>>Spire.Doc系列教程(2):插入、計(jì)數(shù)、檢索和刪除Word文檔變量
Spire.Doc系列教程(2):插入、計(jì)數(shù)、檢索和刪除Word文檔變量
插入變量
Document.Variables屬性可以獲取一個(gè)Variables集合(VariableCollection),該集合表示存儲在文檔中的變量。使用VariableCollection.Add(string name, string value) 方法,可以插入變量到文檔。
以下示例添加了一個(gè)名為“A1”,值為12的變量到一個(gè)Word文檔。
//初始化document對象 Document document = new Document(); //添加節(jié) Section section = document.AddSection(); //添加段落 Paragraph paragraph = section.AddParagraph(); //添加DocVariable域 paragraph.AppendField("A1", FieldType.FieldDocVariable); //添加文檔變量到DocVariable域 document.Variables.Add("A1", "12"); //更新域 document.IsUpdateFields = true; //保存并關(guān)閉文檔 document.SaveToFile("AddVariable.docx", FileFormat.Docx2013); document.Close();

計(jì)算變量個(gè)數(shù)
VariableCollection.Count屬性可以計(jì)算文檔中的變量個(gè)數(shù)。
//Load the document Document document = new Document("添加變量.docx"); //Get the number of variables in the document int number = document.Variables.Count; Console.WriteLine(number);

檢索變量
Spire.Doc支持使用index來檢索指定變量的名稱和對應(yīng)的值,同時(shí)也支持直接使用變量的名稱來檢索或設(shè)置值。
//加載文檔 Document document = new Document("添加變量.docx"); // 使用index檢索變量的名稱 string s1 = document.Variables.GetNameByIndex(0); // 使用index檢索變量的值 string s2 = document.Variables.GetValueByIndex(0); // 使用變量名稱檢索變量的值 string s3 = document.Variables["A1"]; Console.WriteLine("{0} {1} {2}", s1, s2, s3);

刪除變量
VariableCollection.Remove(String name) 方法可以刪除文檔中的指定變量,參數(shù)為該變量的名稱。