0

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.

  • 1
    the easiest would be to work with `docx` and drop some tokens in the field where you wanted. then use [aspose find and replace](https://docs.aspose.com/words/net/find-and-replace/) feature. but if you have to work with `dotx`, is your "field" actually a proper field? if yes, you can use [mail merge thing](https://docs.aspose.com/words/net/mail-merge-and-reporting/). its all depends on the file you want to play with - how its constructed. – Bagus Tesa Jun 15 '22 at 09:09
  • also, if you dont dealing with pdf, dont pollute [tag:aspose.pdf] tag. please use relevant tags. – Bagus Tesa Jun 15 '22 at 09:10

1 Answers1

1

In your case you can use either Mail Merge or LINQ Reporting Engine. In case of using Mail Merge, you should insert merge fields where values must be inserted. Your template will look like the following: 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 specials syntax. The template should look like this: 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.

Alexey Noskov
  • 1,722
  • 1
  • 7
  • 13