I'm using the WordTemplate from softartisans to generate a report. Some part of the report may not have data. How do I remove a section from the generated Word document when the data is null?
I would appreciate any assistance.
Thanks.
I'm using the WordTemplate from softartisans to generate a report. Some part of the report may not have data. How do I remove a section from the generated Word document when the data is null?
I would appreciate any assistance.
Thanks.
Try checking the data to be inserted for null-value before adding it to the document. Usually, replacing null with an empty string does the trick. I'd help with the code if there was any.
One way to accomplish this is to put bookmarks around the optional sections in your template and use the BookmarksToRemove method (introduced in version 8.4) to tell the WordTemplate object which sections to remove. This method takes a string array of bookmark names. Your code would need to determine which bookmarked sections do not contain data.
WordTemplate wt = new WordTemplate();
wt.Open(@"c:\templates\Template.docx");
string [] bookmarks = {"OptionalSection1", "OptionalSection2"};
wt.BookmarksToRemove(bookmarks);
wt.Process();
wt.Save(@"c:\reports\Report.docx");
Another option is to use IF fields in your Word template file. You can use conditional logic in an IF Field to show or hide an entire section of the document depending on the value in a particular merge field. In order for OfficeWriter to calculate the IF fields on the server, you need to turn on the UpdateIfFields property. If you want the IF Fields to be removed after they are evaluated, you can use the UnlinkIfFields property (introduced in version 8.1)
WordTemplate wt = new WordTemplate();
wt.UpdateIfFields = true;
wt.UnlinkIfFields = true;
The advantage of using IF fields is that empty results in your data can be handled automatically. The drawback of using IF fields is that it can make the template more complicated to build. That may or may not be an issue for you depending on whether your templates are being created by users or developers.