C# – Update Word Formula Fields

Word fields are placeholders that store and display data. They perform simple tasks, such as returning the current date or current page number, but they’re much more than that. You can use them to ask questions, make decisions based on specific conditions, and perform calculations.

Just because a field contains dynamic text doesn’t mean that the field is always accurate. Occasionally, fields need updating. Assume you have an involve template (like Figure 1) which contains formula fields in the table cells where ‘0.0’ appears, you’d like to insert some necessary information in the invoice and update the fields automatically. This is what I am intending to do in this article.

2018-01-16_155023Figure 1. Template Word File

Still, I am using Spire.Doc library to complete this job. Here is the entire code.

using Spire.Doc;

namespace UpdateField
    class Program
        static void Main(string[] args)
            //create a document instacne
            Document doc = new Document();

            //load the template file

            //replace data in the document
            doc.Replace("a.description", "Product A", true, true);
            doc.Replace("b.description", "Product B", true, true);
            doc.Replace("c.description", "Product C", true, true);
            doc.Replace("a.quantity", "1", true, true);
            doc.Replace("b.quantity", "2", true, true);
            doc.Replace("c.quantity", "1", true, true);
            doc.Replace("a.price", "14", true, true);
            doc.Replace("b.price", "10", true, true);
            doc.Replace("c.price", "23", true, true);

            //update fields
            doc.IsUpdateFields = true;
            //save to file
            doc.SaveToFile("output.docx", FileFormat.Docx2013);
Figure 2. Result File

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s