Automation for using Word 2007 in VS.NET 2005 IDE without creating word object
This is an alternate for word document object using the System.IO.Packaging in VS.NET 2005.
You can able to create, open a document using XML and make any type of changes there, just like you do word object (letterApp = new Word.ApplicationClass ();)
Just add the reference to windowsbase.dll from directory "c:\Program Files\Reference Assemblies\Microsoft".
This will work only for MS Word 2007. It does not support backward compatability.
Open a C# project, add the reference to windowsbase.dll and the create new form and place the below code. pass the file (created in word 2007 extension should be .docx) , search string and replacement string. Try to run the application the old text will be replaced by the new one.
private bool SearchDocx(string strfile, string searchFor,string strReplace)
{
try
{
using (Package myPackage = Package.Open(strfile, FileMode.Open, FileAccess.ReadWrite))
{
PackagePart documentPart = null;
const string documentRelationshipType =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
foreach (PackageRelationship relationship in myPackage.GetRelationshipsByType(documentRelationshipType))
{
documentPart = myPackage.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri));
break;
}
XmlDocument doc = new XmlDocument();
doc.Load(documentPart.GetStream());
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
string StrQuery = "//w:t[text()='" + searchFor + "']";
bool bolReplace=false;
foreach (XmlNode sdtNode in doc.SelectNodes(StrQuery, nsmgr))
{
sdtNode.InnerText = strReplace;
bolReplace = true;
}
documentPart.GetStream().Seek(0, SeekOrigin.Begin);
documentPart.GetStream().SetLength(0);
doc.Save(documentPart.GetStream());
if (bolReplace == false)
{ return false; }
else
{ return true; }
}
}
catch
{
MessageBox.Show("Could not Open file: " + strfile);
return false;
}
}
Thanks.
Like it on Facebook, Tweet it or share this article on other bookmarking websites.