Hi, i am writing a c# code to open a word file using Application and Document object and read a particular line in a existing template word file and repeat that line in the next line. I could able to read and paste it in the next line using Bookmark and Range objects. But, i could not able to get the styles/formats like bold/italics/underline.
I want to read the line and paste it with the same style.
I am attaching a small code, which i am trying, please help me in this and let me know, if bookmark and range is the correct approach.
**Example in word file:**
[OpeningTagStart]
This line will *repeat* along with **[Values]**
[/OpeningTagStart]
**The code snippet is as follows:**
//reading the template file
myWordDoc = new Document();
myWordApp = new Application();
Object filename = null;
Object BookMark_StartTag;
Object BookMark_EndTag;
filename = Server.MapPath("Templates\\MyTemplate.doc");
myWordDoc = myWordApp.Documents.Add(ref filename, ref NotTrue, ref Missing, ref Missing);
myWordApp.Visible = false;
//bookmark in template. This will be done programatically
//opening tag will have "start" and closing tag will have "end" as bookmark
BookMark_StartTag = "start";
BookMark_EndTag = "end";
//selecting the range between the opening and closing tag
//by fixing the end of opening tag range and start of closing tag range.
Object StartRange = myWordDoc.Bookmarks.get_Item(ref BookMark_StartTag).Range.End;
Object EndRange = myWordDoc.Bookmarks.get_Item(ref BookMark_EndTag).Range.Start;
Range SelectRange = myWordDoc.Range(ref StartRange, ref EndRange);
SelectRange.Select();
//Fix another range, which will be the next line of the selected range
//This range is required to paste the text from the selected range
Object NextLineRange = SelectRange.End;
//get the style of the selected range
Object style = SelectedRange.get_Style();
//paste the text of the selected range in the next line range
//This will repeat in a loop for multiple lines
myWordDoc.Range(ref NextLineRange, ref Missing).Text = SelectRange.Text.Replace("\r", "").Trim();
//Apply the style of the selected range to the text in next line range
myWordDoc.Range(ref NextLineRange, ref Missing).set_Style(ref style);
The above code is pasting the text in the next line but not applying the styles. Please let me know, if the approach for retaining the style is correct.
Eagerly waiting for your early responses.
Thanks,
Rajkumar
No one has replied yet! Why not be the first?
Sign in or Join us (it's free).