Skip to content

Instantly share code, notes, and snippets.

@fileformat-words-gists
Last active December 16, 2023 17:50
Show Gist options
  • Save fileformat-words-gists/53dbf77cd1168f06320f4b1a447bc4d1 to your computer and use it in GitHub Desktop.
Save fileformat-words-gists/53dbf77cd1168f06320f4b1a447bc4d1 to your computer and use it in GitHub Desktop.
C# Modify Word Document Paragraphs
/// <summary>
/// Loads a Word Document with structured content using
/// <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>.
/// Modifies paragraphs by prepending 'Modified Heading :' for styled paragraphs
/// and 'Modified Run :' for each run within normal paragraphs, preserving the existing format.
/// Saves the modified Word Document.
/// </summary>
/// <param name="documentDirectory">
/// The directory where the Word Document to load is present and
/// the modified document will be saved (default is the the root of your project).
/// </param>
/// <param name="filename">
/// The name of the Word Document file to modify (default is "WordParagraphs.docx" - please replace it
/// with your word document present at the directory defined by documentDirectory).
/// </param>
/// <param name="filenameModified">
/// The name of the modified Word Document (default is "ModifiedWordParagraphs.docx") to be saved to the directlry
/// defined by documentDirectory.
/// </param>
public void ModifyWordParagraphs(string documentDirectory = docsDirectory,
string filename = "WordParagraphs.docx", string filenameModified = "ModifiedWordParagraphs.docx")
{
try
{
// Load the Word Document
var doc = new FileFormat.Words.Document($"{documentDirectory}/{filename}");
var body = new FileFormat.Words.Body(doc);
foreach (var paragraph in body.Paragraphs)
{
foreach (var run in paragraph.Runs)
{
// Prepend 'Modified Heading :' for styled paragraphs
// and 'Modified Run :' for each run within normal paragraphs, preserving the existing format
run.Text = paragraph.Style.Contains("Heading") ? $"Modified Heading: {run.Text}" : $"Modified Run : {run.Text}";
}
// Update the paragraph in the document
doc.Update(paragraph);
}
// Save the modified Word Document
doc.Save($"{documentDirectory}/{filenameModified}");
Console.WriteLine($"Word Document {filename} Modified and Saved As {filenameModified}. Please check directory: {Path.GetFullPath(documentDirectory)}");
}
catch (Exception ex)
{
throw new FileFormat.Words.FileFormatException("An error occurred.", ex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment