I have been able to perform a mail merge successfully using a word document and datatable. This mail merge outputs one large word document for all the records in the datatable. Is there a way to generate a seperate word document for each record in the datatable. I don’t want to perform multiple mail merges one for each record. I want to be able to run mail merge once, have a user review the concatenated document than split the document into multiple documents one for each record in the datatable… Any help is very much appreciated
Hi
Thanks for your inquiry. If you use simple mail merge then new section will be created for each record in your data source. So you can split the document using sections. Please see the following code:
public void Test200()
{
// Create dummy datasource
DataTable table = new DataTable();
table.Columns.Add("FirstName");
table.Columns.Add("LastName");
table.Columns.Add("Company");
// Add few recods into the datatable
table.Rows.Add(new object[] { "Alexey", "Noskov", "Aspose" });
table.Rows.Add(new object[] { "Steve", "Smith", "IBM" });
table.Rows.Add(new object[] { "Den", "King", "Microsoft" });
// Open template
Document doc = new Document(@"Test200\in.doc");
// Execute mail merge
doc.MailMerge.Execute(table);
// Save output document
doc.Save(@"Test200\fullOutput.doc");
// Split the document
StlitDocument(doc, @"Test200\");
}
private void StlitDocument(Document doc, string outputFolder)
{
// Loop through all sections in the document
// And save each section in the separate document
int index = 0;
foreach (Section sect in doc.Sections)
{
// Create new document
Document dst = new Document();
// Remove all sections
dst.FirstSection.Remove();
// Import section from the source document
dst.Sections.Add(dst.ImportNode(sect, true, ImportFormatMode.KeepSourceFormatting));
// Save doucument
dst.Save(outputFolder + string.Format("out_{0}.doc", index));
index++;
}
}
The template document is attached. Hope this could help you. Please let me know in case of any issues. Also please attach your document for testing.
Best regards.