Hello,
I have a Word document in docx format and mail merge with Excel in xls format.
The following are mergefields that rendered properly in Word but not when I do mail merge in my code.
{ MERGEFIELD TODAY \@ “MM/dd/yy” }
{ MERGEFIELD BAL \# ####,0.00 }
The following code:
using (Stream stream = new FileStream(docxPath +docxFilename, FileMode.Open)) { stream.Seek(0, SeekOrigin.Begin); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); templateDocument = new DocxFormatProvider().Import(bytes); IEnumerable mailMergeSource = this.GetMailMergeDataSource(worksheet); mergeDocument = templateDocument.MailMerge(mailMergeSource); this.SaveFile(mergeDocument); }
Above is the main code that do mailmerge
The GetMailMergeDataSource is give below:
private IEnumerable GetMailMergeDataSource(Worksheet worksheet)
{
List<DynamicDataObject> mailMergeSource = new List<DynamicDataObject>();
string[] fieldNames = new string[worksheet.UsedCellRange.ColumnCount];
int columnCount;
int rowCount;
CellSelection selection;
for (columnCount = 0; columnCount < worksheet.UsedCellRange.ColumnCount; columnCount++)
{
selection = worksheet.Cells[0, columnCount];
fieldNames[columnCount] = selection.GetValue().Value.RawValue.ToString();
}
for (rowCount = 1; rowCount < worksheet.UsedCellRange.RowCount; rowCount++)
{
DynamicDataObject data = new DynamicDataObject();
for (columnCount = 0; columnCount < worksheet.UsedCellRange.ColumnCount; columnCount++)
{
selection = worksheet.Cells[rowCount, columnCount];
data.Set(fieldNames[columnCount], selection.GetValue().Value.RawValue);
}
if (columnCount > 0)
mailMergeSource.Add(data);
}
return mailMergeSource;
}
DynamicDataaObject is derived from Telerik own's sample document-processing-sdk-master > WordsProcessing
the SaveFile is below:
private void SaveFile(RadFlowDocument document) { using (Stream stream = File.OpenWrite(newDocxPath + newDocxFilename)) { DocxFormatProvider formatProvider = new DocxFormatProvider(); DocxExportSettings exportSettings = new DocxExportSettings { AutoUpdateFields = true, InvalidDocumentAction = InvalidDocumentAction.ThrowException }; formatProvider.ExportSettings = exportSettings; formatProvider.Export(document, stream); } }
It works. It merged into another docx document but the Merge Field format failed. But to do the same with Word merge, the resulting file shows proper format.
Let me know if you need full working sample that demo the problem.
Thank,