I am having trouble trying to remove a list of data/text from a Word document using Word Interop. So far I thought that I could read through the document to find the starting text, then find the ending text, and save each of those index's to their own variable. Next I would just loop through the data from the starting index to the ending index and delete all the text in between.
Problem is that it works incorrectly and doesn't provide expected results. I must not be understanding how the Range
interface works in document.Paragraphs[i+1].Range.Delete();
. It deletes some lines but not all, and seems to go beyond the paragraphs that I care about to delete. What am I missing? There must be a better way to do this. Documentation seems low with Interop.
string text = " ";
int StartLocation = 0;
int EndLocation = 0;
//I roughly know the starting location
//starting at I=2248 so I don't
//through entire document
for (int i = 2248; i < 2700; i++)
{
text = document.Paragraphs[i + 1].Range.Text.ToString();
if (text.Contains("firstWordImSearchingFor"))
{
StartLocation = i;
}
if (text.Contains("lastWordImSearchingFor"))
{
EndLocation = i;
}
}
//delete everything between those paragraph locations
//(not working correctly/ skips lines)
for(int i = StartLocation; i<EndLocation-1i++)
{
document.Paragraphs[i+1].Range.Delete();
}
how to remove text from a word doc C# Microsoft.Interop
look at this for some possible pointers as well stackoverflow.com/questions/10231132/… – MethodMan.docx
files and not.doc
files I would recommend you stop using the interop classes and switch to the newer SDK Microsoft released specifically for working withdocx
files. – Scott Chamberlaindocx
generation/modification? – trailmax