I am evaluating Aspose Word and have found that merge causes an error in the Word file. The merges are completed but Word says that the file has an error and tries to recover.
Here are the methods I use:
public void PrepareReport(string templateFileName, Hashtable reportData, string outputFileName)
{
string[] fieldNames = new string[reportData.Keys.Count];
string[] values = new string[reportData.Keys.Count];
int index=0;
foreach(string key in reportData.Keys)
{
fieldNames[index] = key;
values[index] = (string)reportData[key];
index++;
}
WordMerge(templateFileName, outputFileName, fieldNames, values);
}
private void WordMerge(string inFileName, string outFileName, string[] fieldNames, object[] values)
{
FileStream inStream = File.OpenRead(inFileName);
FileStream outStream = File.OpenWrite(outFileName);
try
{
Word word = new Word();
Document doc = word.Open(inStream);
doc.MailMerge.Execute(fieldNames, values);
doc.Save(outStream, SaveFormat.FormatDocument);
}
finally
{
if(inStream != null)
{
inStream.Close();
}
if(outStream != null)
{
outStream.Close();
}
}
}
Here is how it is called:
private static void complexMergeTest()
{
WordDocumentUtil test = new WordDocumentUtil();
string inFileName = @"C:\Projects\TestAsposeWord\TemplateFiles\LoadMergeText.doc";
string outFileName = @"C:\Projects\TestAsposeWord\OutputFiles\complexMerge.doc";
Hashtable mergeData = new Hashtable();
mergeData.Add("headerItem", "HeaderCrap");
mergeData.Add("titleItem", "Title Crap");
mergeData.Add("andAuthor", "Author Crap");
mergeData.Add("listItem", "More Crap");
mergeData.Add("chartItem", "Chart Crap");
mergeData.Add("tableItem", "Table Crap");
test.PrepareReport(inFileName, mergeData, outFileName);
}