Using DocX to Replace Words
by clayshannon
HTML
<h1>How to Replace a List of words in a .DOCX file using the DocX Library</h1>
<h2>Mission</h2>
<p>I recently came upon a tedious need to replace a slew (not slough) of words in a long document (the 1885 translation of Miguel de Cervantes' <cite>Don Quixote</cite>).</p>
<p>Specifically, I wanted to replace the British spellings of words with their American dialect equivalent. For example, I wanted to replace "colour" with "color", "centre" with "center", "plough" with "plow" etc.</p>
<p>I could replace these one word at a time using Find > Replace, but that quickly becomes a pain in the arse...I mean, donkey. After all, WE BE PROGRAMMERS!</p>
<p>So, I located a handy library for working with .docx files named, appropriately if dully or even near-redundantly, <a href="https://docx.codeplex.com/">DocX</a></p>
<h2>Commission</h2>
<p>To use the docx library, simply download it (docx.dll), add a reference to it in your project, and then this using clause:</p>
<pre>using Novacode;</pre>
<p>You first need to load the document that contains the "fawlty" spellings, like so (this assumes you have dropped an openfiledialog control on a Windows Forms form, and kept the default name (openfiledialog1):</p>
<pre>
string filename = string.Empty;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog1.FileName;
}
else
{
MessageBox.Show("No file selected - hasta la vista and Ciao, baby!");
return;
}
using (DocX document = DocX.Load(filename))
{
document.ReplaceText("travelled", "traveled");
document.Save();
}
</pre>
<p>But, of course, we want to do all the words at once. First, we need to have that list of words, so code like this is...