Free Support Forum - aspose.com

Fields update

I have a template word document which contains some DOCVARIABLE,


I want to update those VARIABLE with new Text, like updating [Company] to 'HP', 'IBM', updating NAME to 'Tom', 'Jack', programmatically of course

Now I have successfully retrieve those DOCVARIABLE like below in c#:

Document doc = new Document("a doc");
NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true, false);
foreach (FieldStart fieldStart in fieldStarts)
{
if (fieldStart.FieldType.Equals(FieldType.FieldDocVariable))
{
//how to upate these fields?
}
}

How do I update these fields?

Hello

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your request. In this case you should use the following code:

Document doc = new Document("in.doc");

doc.Variables["VariableName"] = "VariableValue";

// We need to update fields before saving

doc.UpdateFields();

doc.Save("out.doc");

Best regards,

Thanks for the reply!

It is not working.

I checked the doc.Variables.Count, it is 0, I actually have 13 variables there.

Hello

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thanks for your inquiry. Could you please attach your document here for testing? I will check the problem on my side and provide you more information.

Best regards,

Hello

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thank you for additional information. I cannot reproduce the problem on my side using the latest version of Aspose.Words (9.4.0). I use the following code for testing:

Document doc = new Document("test.doc");

doc.Variables["UserName"] = "Andrey";

doc.Variables["UserCompany"] = "Aspose";

doc.Variables["UserAddress"] = "Address";

// We need to update fields before saving

doc.UpdateFields();

doc.Save("out.doc");

You can download the latest version from here:

http://www.aspose.com/community/files/51/.net-components/aspose.words-for-.net/category1188.aspx

Please see the attached document produced on my side.

Best regards,

Sorry, I checked the wrong output path, the code you provided actually works!

But the interesting thing is that variable.count is always 0. :(

Hello

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thank you for additional information. If you will try getting variables count from out.doc (from my previous post), you will get the count 3.

Document doc = new Document("out.doc");

Console.WriteLine(doc.Variables.Count);

{DOCVARIABLE Name \* MERGEFORMAT} is just “link” to the appropriate variable. Variable appears inside a document only after initialization.

Best regards,