Document variables are key-value pairs stored inside a document, and both the name and the value are strings. The variables themselves do not appear in the body; only when a DOCVARIABLE field refers to a variable does the field result appear on the page. Variables suit the business fields that travel with a document, such as a purchase quantity, an equipment number, and a delivery date; after a value is changed and the fields are updated, the values in the body change with it.
Spire.Doc for C++ returns a VariableCollection through Document->GetVariables(), adds variables with Add(), counts them with GetCount(), reads keys and values by index with GetNameByIndex() and GetValueByIndex(), reads a value by name with GetItem(), and removes variables with Remove(). The combination of variables and fields is completed through Paragraph->AppendField() and FieldType::FieldDocVariable.
This article covers three features:
- Add a variable and insert a DocVariable field
- Read and count document variables
- Remove a variable by name
The sample uses "Equipment Procurement List for the Warehouse No. 2 Automation Upgrade" (Variables.docx), whose three values are supplied by document variables:

Install Spire.Doc for C++
There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.
- In Visual Studio, open the NuGet Package Manager, search for
Spire.Doc.Cpp, and install it. - Alternatively, run
nuget install Spire.Doc.Cppin the project directory, and then add the package'sincludeandlibfolders to the project.
An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.
Reading and writing document variables involves the following members:
| Member | Purpose |
|---|---|
Document->GetVariables() |
Returns the document variable collection |
VariableCollection->Add(name, value) |
Adds a variable |
VariableCollection->GetCount() |
Returns the number of variables |
GetNameByIndex(index) / GetValueByIndex(index) |
Reads the key and the value by index |
GetItem(name) / SetItem(name, value) |
Reads and modifies a value by name |
VariableCollection->Remove(name) |
Removes a variable by name |
Paragraph->AppendField(code, FieldType::FieldDocVariable) |
Inserts a DocVariable field |
Document->SetIsUpdateFields(true) |
Updates fields when the document is saved |
Add a Variable and Insert a DocVariable Field
Adding a variable writes only to the document variable table and produces no visible content in the body. To make the value appear, insert a DOCVARIABLE field in a paragraph, with the variable name in the field code matching the variable key, and enable field updating before saving. The example appends a line "Purchase Quantity: " at the end of the report, inserts a field that refers to the variable A1, and then sets the value of A1 to 12.
| Operation | Method |
|---|---|
| Write the label text | Paragraph->AppendText(text) |
| Insert the DocVariable field | Paragraph->AppendField("A1", FieldType::FieldDocVariable) |
| Add the variable with the same name | GetVariables()->Add("A1", "12") |
| Update fields on save | Document->SetIsUpdateFields(true) |
The detailed steps are as follows.
- Create a Document object and call LoadFromFile() to load the sample document.
- Obtain the first section and call AddParagraph() to add a paragraph at the end of the body.
- Call AppendText("Purchase Quantity: ") to write the label text.
- Call AppendField("A1", FieldType::FieldDocVariable) to insert the field.
- Call GetVariables()->Add("A1", "12") to add the variable, and then call SetIsUpdateFields(true).
- Call SaveToFile() to save the document.
The code for adding the variable and the field is shown below.
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/FieldType.h"
#include "Spire/Doc/Fields/Field.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/VariableCollection.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
int main()
{
SetConsoleOutputCP(CP_UTF8);
//Load the project progress report
intrusive_ptr<Document> document = new Document();
document->LoadFromFile("Template.docx");
intrusive_ptr<Section> section = document->GetSections()->GetItem(0);
//Append the label text and the DocVariable field to the end of the body
intrusive_ptr<Paragraph> paragraph = section->AddParagraph();
paragraph->AppendText("Purchase Quantity: ");
intrusive_ptr<Field> field = paragraph->AppendField("A1", FieldType::FieldDocVariable);
//Add the variable with the same name; update fields on save
document->GetVariables()->Add("A1", "12");
document->SetIsUpdateFields(true);
cout << "Variable count: " << document->GetVariables()->GetCount() << endl;
cout << "Value of A1: " << document->GetVariables()->GetItem("A1") << endl;
//Save and close the document
document->SaveToFile("Output/AddVariables.docx", FileFormat::Docx);
document->Close();
return 0;
}
The console output shows that the variable has been added and its value is 12:
Variable count: 1
Value of A1: 12
After saving, the document adds "Purchase Quantity: 12" below the table, where 12 comes from the field result of the DocVariable field:

The Variable Itself Is Not Displayed in the Body
GetVariables()->Add() modifies only the document variable table and produces no page content. The "12" is visible in the example because a DOCVARIABLE A1 field is inserted in the paragraph and the fields are updated on save. When only a variable is added without a field, the body does not change at all, and the variable does not appear in the file properties either.
The Name in the Field Code Must Match the Variable Name
The first parameter of AppendField("A1", FieldType::FieldDocVariable) is the field code, that is, the variable name after DOCVARIABLE. The name is case-sensitive and must be exactly the same as the key passed to Add("A1", ...). When the names differ, the field has no result after updating, and the page shows only the label text.
Updating Fields Is Triggered by the Save Operation
SetIsUpdateFields(true) tells the document to update all fields when it is saved. The example adds the variable first, then enables updating, and the DOCVARIABLE field takes the value of A1 on save. Without this setting, the saved document keeps the previous field result and the fields must be updated manually in Word. The variable value and the field result can be out of sync, so the fields should be saved again or updated after a value is changed.
Read and Count Document Variables
Reading is done through VariableCollection. GetCount() returns the total number; GetNameByIndex() and GetValueByIndex() return the key and the value by index, which suits iteration; GetItem(name) reads a single value by name. The example loads a procurement list with three variables, outputs all the key-value pairs, and then reads B1 by name.
| Operation | Method | Return type |
|---|---|---|
| Count the variables | GetCount() |
int |
| Get the key by index | GetNameByIndex(index) |
string |
| Get the value by index | GetValueByIndex(index) |
string |
| Get the value by name | GetItem(name) |
string |
| Set the value by name | SetItem(name, value) |
void |
The detailed steps are as follows.
- Create a Document object and call LoadFromFile() to load the document that contains the variables.
- Call GetVariables() to obtain the variable collection.
- Call GetCount() to output the number of variables.
- Use a loop with GetNameByIndex() and GetValueByIndex() to iterate over all the variables.
- Call GetItem("B1") to read the equipment number by name.
The code for reading and counting the variables is shown below.
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/VariableCollection.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;
int main()
{
SetConsoleOutputCP(CP_UTF8);
//Load the procurement list with three document variables
intrusive_ptr<Document> document = new Document();
document->LoadFromFile("Variables.docx");
intrusive_ptr<VariableCollection> variables = document->GetVariables();
//Output the variable count and all key-value pairs
cout << "Variable count: " << variables->GetCount() << endl;
for (int i = 0; i < variables->GetCount(); i++)
{
cout << variables->GetNameByIndex(i) << " = "
<< variables->GetValueByIndex(i) << endl;
}
//Read a single variable by name
cout << "Value of B1 by name: " << variables->GetItem("B1") << endl;
document->Close();
return 0;
}
The console outputs the three variables in the order of addition and reads the value of B1 by name:
Variable count: 3
A1 = 12
B1 = WH-2026-08
C1 = 2026-12-15
Value of B1 by name: WH-2026-08
The Index Order Matches the Order of Addition
GetNameByIndex() and GetValueByIndex() use the position of a variable in the collection, and the order follows the document variable table. The three variables in the example are output as A1, B1, and C1. Call GetCount() before iterating to obtain the current number, and do not assume a fixed value in the loop condition; after a variable is removed, the indexes of the following elements move forward.
Reading by Name Suits Business Fields
Business code usually knows the field names and does not care about the storage order, so GetItem("B1") reads the value directly without iterating first. The key must exactly match the name in the variable table; to confirm that a variable exists, iterate over GetNameByIndex() and compare the keys. To modify a value, call SetItem(name, value), and after the change the document must also be saved and the fields updated.
Reading a Variable Does Not Update the Field Result
The value in the variable collection and the value shown by the field result in the body are two separate pieces of data. The example reads the variable table and does not trigger a field update. If a variable is changed after the document is opened, the body still shows the old result until the fields are updated. When the body is authoritative, read the field result; when the data is authoritative, read the variable collection.
Remove a Variable by Name
Variables are removed with VariableCollection->Remove(name), whose parameter is the key. After removal the variable is gone from the collection, and a DOCVARIABLE field that referred to it has no result after updating. The example outputs the count before removal, removes B1, and then outputs the count after removal and saves the document.
| Operation | Method | Description |
|---|---|---|
| Remove a variable | Remove(name) |
Removes by name |
| Count before removal | GetCount() |
Returns the current number |
| Count after removal | GetCount() |
The number decreases by one |
| Update fields | SetIsUpdateFields(true) |
Clears the field result on save |
The detailed steps are as follows.
- Create a Document object and call LoadFromFile() to load the document that contains the variables.
- Call GetCount() to output the number of variables before removal.
- Call Remove("B1") to remove the equipment number variable.
- Call SetIsUpdateFields(true), and output the number after removal again.
- Call SaveToFile() to save the result document.
The code for removing the variable is shown below.
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/VariableCollection.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;
int main()
{
SetConsoleOutputCP(CP_UTF8);
//Load the procurement list with three document variables
intrusive_ptr<Document> document = new Document();
document->LoadFromFile("Variables.docx");
intrusive_ptr<VariableCollection> variables = document->GetVariables();
cout << "Variable count before removal: " << variables->GetCount() << endl;
//Remove the equipment number variable by name and update fields on save
variables->Remove("B1");
document->SetIsUpdateFields(true);
cout << "Variable count after removal: " << variables->GetCount() << endl;
//Save and close the document
document->SaveToFile("Output/RemoveVariables.docx", FileFormat::Docx);
document->Close();
return 0;
}
The console output shows that the number of variables falls from 3 to 2:
Variable count before removal: 3
Variable count after removal: 2
After saving, the value after "Equipment Number" is cleared, and the other two variables and the body remain unchanged:

Removing a Variable Does Not Remove the Field
Remove("B1") deletes only the key-value pair in the variable table, and the DOCVARIABLE B1 field in the paragraph still exists. After saving and updating the fields, the field result is empty and only the label text remains on the page. If a variable with the same name is added again and the fields are updated, the value reappears. To remove the field as well, delete the field object in the paragraph according to the field structure.
Removal Order Affects Reading by Index
After a variable is removed, the indexes of the variables after it move forward. The example removes by name and does not depend on indexes, so the result is stable. When removing by index, start from the last element to avoid index misalignment after a removal. For batch removal, call GetCount() and GetNameByIndex(0) in a loop and remove the first item of the collection each time.
The Removal Takes Effect After Saving
Remove() modifies the variable collection in memory, and the change is written to the file only after SaveToFile() is called. The example saves immediately after the removal, and the result document no longer contains B1. When only removal is performed without saving, the original file remains unchanged; if a variable with the same name is added after the removal, only the new value remains in the collection.
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
