Reputation: 13
I want to create a doc file and copy some of the content to another doc file using word interop and c# .e.g
This is my doc file.I will paste only this part to another doc file. Rest of the text will remain here only.
I just want to paste the text "I will paste only this part to another doc file.Rest of " to another DOc file. can anyone helpme to get the range of this line from the document I am using Interop but want to get the range upto particular word from the doc file and than select text upto that range to copy it to another doc file..I want to know the method to get the range
Upvotes: 1
Views: 3171
Reputation: 11104
If the doc can be DOCX then there's very easy DOCX wrapper you can use. It's realy simple to merge documents, change parts of text, find and replace only some words. Author has made lots of good tutorials on how to use it on his Blog site.
If however you want DOC then you have to use Interop.
For example if you want to find some word and replace it with another you would do it like suggested on the blog:
This version of DocX allows you to search a document for a string. The function FindAll(string str) returns a list containing all of the start indexes of the found string. Below is an example of this new function.
// Load a document
using (DocX document = DocX.Load(@"Test.docx"))
{
// Loop through the paragraphs in this document.
foreach (Paragraph p in document.Paragraphs)
{
// Find all instances of 'go' in this paragraph.
List<int> gos = document.FindAll("go");
/*
* Insert 'don't' in front of every instance of 'go' in this document to produce * 'don't go'. An important trick here is to do the inserting in reverse document * order. If you inserted in document order, every insert would shift the index * of the remaining matches.
*/
gos.Reverse();
foreach (int index in gos)
{
p.InsertText(index, "don't ", true);
}
}
// Save all changes made to this document.
document.Save();
}// Release this document from memory.
For DOC and searching for particular string maybe you could copy whole doc to the clipboard and find what you need, cut it out:
Word.ApplicationClass wordApp=new ApplicationClass();
object file=path;
object nullobj=System.Reflection.Missing.Value;
Word.Document doc = wordApp.Documents.Open(ref file, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data=Clipboard.GetDataObject();
txtFileContent.Text=data.GetData(DataFormats.Text).ToString();
doc.Close();
Keep in mind to release resources or you will end up with lots of word.exe processes open up.
Here's also a good reading which can help you out.
Couple of articles you may wanna read:
How to: Search for Text in Documents
How to: Search for and Replace Text in Documents
Upvotes: 1