Home > Net >  Filling Data according to a Template file(DOTX) using Aspose .NET
Filling Data according to a Template file(DOTX) using Aspose .NET

Time:06-17

I have a MS word template file (DOTX). It has Header, Footer and Body. Inside body, there are some labels like

Header

Emp ID:

Emp Name:

Footer

Now I need to fill up those labels with data using Aspose Words .Net

My task is to generate the doc files for multiple Employees with help of this template.

I have seen many solutions but couldn't understand how to fetch those labels and fill them up . Should the template must contain bookmarks or fields? I have tried "doc.BuiltInDocumentProperties" and "doc.CustomDocumentProperties", but these are not giving those required labels.

So Can anyone guide me or help me doing this task.

CodePudding user response:

In your case you can use either enter image description here Then you can use the following simple code to fill your document with data:

Document doc = new Document(@"C:\Temp\in.docx");
string[] fieldNames = new string[] { "EmpID", "EmpName" };
string[] fieldValues = new string[] { "007", "James Bond" };
doc.MailMerge.Execute(fieldNames, fieldValues);
doc.Save(@"C:\Temp\out.docx");

In case of using LINQ Reporting Engine, instead of MS Word merge fields, you should use enter image description here And the following code to fill the template with data:

// In LINQ Reporting Engine you can use variouse data sources,
// For demonstraction purposes use JSON.
string json = "{ \"EmpID\" : \"007\", \"EmpName\" : \"James Bond\" }";
Document doc = new Document(@"C:\Temp\in.docx");
ReportingEngine engine = new ReportingEngine();
JsonDataSource dataSource = new JsonDataSource(new MemoryStream(Encoding.UTF8.GetBytes(json)));
engine.BuildReport(doc, dataSource);
doc.Save(@"C:\Temp\out.docx");

As alternative not traditional solutions you can also use text placeholders and find/replace feature to replace them with real data or bookmarks as a placeholder for your data.

  • Related