Denis_Sh
Denis_Sh

Reputation: 317

ASP.NET + C#. Creating word document from template

I have a word document which contains only one page filled with text and graphic. The page also contains some placeholders like [Field1],[Field2],..., etc. I get data from database and I want to open this document and fill placeholders with some data. For each data row I want to open this document, fill placeholders with row's data and then concatenate all created documents into one document. What is the best and simpliest way to do this?

Upvotes: 1

Views: 24198

Answers (2)

Akshay Randive
Akshay Randive

Reputation: 384

Instead of some third party i will suggest you openXML

add following namespaces System.Text.RegularExpressions; DocumentFormat.OpenXml.Packaging; and DocumentFormat.OpenXml.Wordprocessing;

public static void SearchAndReplace(string document)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        Regex regexText = new Regex("Hello world!");
        docText = regexText.Replace(docText, "Hi Everyone!");

        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
}

Upvotes: 3

Related Questions