This project has moved. For the latest updates, please go here.

replace text problems wits styles

Mar 18, 2011 at 7:51 PM


i have a problem. i would like to replace text and i have achieved that but the style of replaced text is not the same as in original (input .docx). all replaced text has the same style.

i use MV C# 2010 Express and Word2010. 

this is my code. as you can see i created a form app. hope this is not the issue.

using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Novacode;
using Word = Microsoft.Office.Interop.Word;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        public Form1()

        private void btnAutomate_Click(object sender, EventArgs e)

            DocX document = DocX.Load("C:\\word_template\\test2.docx");
            document.ReplaceText("#ime", txtIme.Text, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            document.ReplaceText("#priimek", txtPriimek.Text, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            document.ReplaceText("#kraj", txtKraj.Text, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            document.ReplaceText("#datum", txtDatum.Text, false, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            document.SaveAs(string.Format(@"C:\word_template\{0}_Geomnia.docx", txtIme.Text));


        private void btnOpen_Click(object sender, EventArgs e)
            Word.Application oWord = new Word.Application();
            Word.Document oWordDoc = new Word.Document();
            oWord.Visible = true;
            object path = string.Format("C:\\word_template\\{0}_Geomnia.docx", txtIme.Text);
            object missing = System.Reflection.Missing.Value;
            oWordDoc = oWord.Documents.Open(ref path,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing);




Moje ime je #ime. Pišem se #priimek. Prihajam iz #kraj.


Datum #datum



Moje ime je Miha. Pišem se Pozauko. Prihajam iz Maribor.


Datum 3.3.2011

Maybe it is something obvisous but i can't figure it out.



and congrats on your project.

best regards,

Miha Požauko

Mar 19, 2011 at 10:02 PM

Hi Miha,

can you please download change set 62851 and tell me if this fixes your problem? DocX should always preserve text formatting on replaceText.

I am sorry it took me so long to reply, I have had a few crazy weeks.

Kind regards,