What we are doing is using merge fields to indicate where we want to
programmatically update data in a document from a database. The user selects
to retrieve what we call a template document from the server for a certain
"file number" in our database. The server then updates our custom merge
fields with data from the database and sends the document down to the client
where it is opened in word. Merge fields seemed like the logical choice
because we can update the result and still maintain the underlying link to
the database through the merge field. Thus if data changes in the database,
the next time the document is pulled, the document will reflect any changes
that have been made. The following is an example of the code we're using:
public void PopulateDocument(some parameters) {
//Open up word with a new document from the template
wa = new Word.ApplicationClass();
wd = wa.Documents.Add(ref templateFile, ref missing, ref missing, ref
trueObject);
wd.Activate();
//Iterate through the fields in the word doc, pull the data from the db and
//update the fields in the word doc
//update the headers and footers
//this code does not work - not sure why the document fields are different
from the header/footer fields in the first place...
foreach (Field hff in
wd.Sections.First.Headers.Item(Word.WdHeaderFooterIndex.wdHeaderFooterPrimar
y).Range.Fields) {
UpdateField(hff,theFileID,theUserID,theOfficeID,theLedgerEntryID);
}
//this code works, but not for the header/footer fields
foreach (Field f in wd.Fields) {
UpdateField(f,theFileID,theUserID,theOfficeID,theLedgerEntryID);
}
}
private void UpdateField(Word.Field theField, int theFileID, int theUserID,
int theOfficeID, int theLedgerEntryID) {
string command = theField.Code.Text.Trim();
//if the merge field starts with the text of our custom command
int index = command.IndexOf(COMMAND_RESWARE);
if (index != -1) {
//populate the result from the database
theField.Result.Text = GetReplacementText(theFileID, theUserID, theOfficeID,
theLedgerEntryID, command.Substring(index + 1 +
COMMAND_RESWARE.Length).Trim());
}
}
"Doug Robbins - Word MVP - DELETE UPPERCASE CHARACTERS FROM EMAIL ADDRESS"