I need to get the contents of a docx file like template , which contains as text content and some identifiers to be changed with other data , and from that template create a single docx with the same content but replicated and with changed values.
As an example, I have a text containing the following content in my document:
Hello
<NOME>
! Welcome! Your address<ENDERECO>
.
And then I need to create another single docx containing something like:
Hello
Fulano 1
! You're welcome ... Your addressENDERECO 1
. HelloFulano 2
! You're welcome ... Your addressENDERECO 2
. HelloFulano 3
! Welcome ... Your addressENDERECO 3
.
Where each line would be at the beginning of a new page.
For this I'm trying something (MAKING A TEST) using the DocX
My example to show the problem:
public static void Main(string[] args)
{
var dictionary = new Dictionary<string, string>();
dictionary.Add("Fulano 1", "Endereco 1");
dictionary.Add("Fulano 2", "Endereco 2");
dictionary.Add("Fulano 3", "Endereco 3");
var template = new FileStream("D:\template.docx", FileMode.Open, FileAccess.Read);
var docs = new List<DocX>();
var x = 0;
foreach (var item in dictionary)
{
x++;
var doc = DocX.Create("D:\temp_NUM.docx".Replace("NUM", x.ToString()));
doc.ApplyTemplate(template, true);
doc.ReplaceText("<NOME>", item.Key);
doc.ReplaceText("<ENDERECO>", item.Value);
doc.Save();
docs.Add(doc);
}
var newDoc = DocX.Create("D:\newDoc.docx");
foreach (var doc in docs)
newDoc.InsertDocument(doc);
newDoc.Save();
}
While using a simple data source, built with a Dictionary
, the data source will be from the system database where it should be deployed.
The temp_1.docx , temp_2.docx and temp_3.docx files are created and the content appears correctly.
But in line newDoc.InsertDocument(doc);
in:
foreach (var doc in docs)
newDoc.InsertDocument(doc);
I get the following error: The string contains no elements . And with that the "merge" is not done.
How do I resolve the issue?