|
| 1 | +using Syncfusion.DocIO; |
| 2 | +using Syncfusion.DocIO.DLS; |
| 3 | +using System.Data; |
| 4 | +using System.IO; |
| 5 | + |
| 6 | +namespace Generate_Documents_for_each_record |
| 7 | +{ |
| 8 | + class Program |
| 9 | + { |
| 10 | + static void Main(string[] args) |
| 11 | + { |
| 12 | + //Open the file as Stream. |
| 13 | + using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open)) |
| 14 | + { |
| 15 | + //Load file stream into Word document. |
| 16 | + using (WordDocument template = new WordDocument(fileStream, FormatType.Docx)) |
| 17 | + { |
| 18 | + //Get the data for mail merge. |
| 19 | + DataTable table = GetDataTable(); |
| 20 | + //Iterate to the each row and generate mail merged document for each rows. |
| 21 | + for (int i = 0; i < table.Rows.Count; i++) |
| 22 | + { |
| 23 | + //Clones the template document for creating new document for each record in the data source |
| 24 | + WordDocument document = template.Clone(); |
| 25 | + //Executes mail merge using the data row. |
| 26 | + document.MailMerge.Execute(table.Rows[i]); |
| 27 | + |
| 28 | + //Create a file stream. |
| 29 | + using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"Output/" + "Record_" + (i + 1) + ".docx"), FileMode.Create, FileAccess.ReadWrite)) |
| 30 | + { |
| 31 | + //Save the Word document to the file stream. |
| 32 | + document.Save(outputFileStream, FormatType.Docx); |
| 33 | + } |
| 34 | + //Releases the resources occupied by WordDocument instance |
| 35 | + document.Dispose(); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + /// <summary> |
| 41 | + /// Get the data for mail merge. |
| 42 | + /// </summary> |
| 43 | + /// <returns></returns> |
| 44 | + static DataTable GetDataTable() |
| 45 | + { |
| 46 | + DataTable table = new DataTable(); |
| 47 | + |
| 48 | + //Defining columns |
| 49 | + table.Columns.Add("Name"); |
| 50 | + table.Columns.Add("Street"); |
| 51 | + table.Columns.Add("City"); |
| 52 | + table.Columns.Add("ProjectNo"); |
| 53 | + |
| 54 | + //Set values |
| 55 | + DataRow row; |
| 56 | + row = table.NewRow(); |
| 57 | + row["Name"] = "Andreas Waning"; |
| 58 | + row["Street"] = "Middelwegg 2"; |
| 59 | + row["City"] = "Vreden"; |
| 60 | + row["ProjectNo"] = "4711"; |
| 61 | + table.Rows.Add(row); |
| 62 | + |
| 63 | + row = table.NewRow(); |
| 64 | + row["Name"] = "Mike Korf"; |
| 65 | + row["Street"] = "teststreet"; |
| 66 | + row["City"] = "TestCity"; |
| 67 | + row["ProjectNo"] = "4711"; |
| 68 | + table.Rows.Add(row); |
| 69 | + |
| 70 | + return table; |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments