Last active
December 16, 2023 17:55
-
-
Save fileformat-words-gists/20db884541540196dd00a9f313d9f77b to your computer and use it in GitHub Desktop.
C# Modify Words Document Tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Loads a Word Document with structured content using | |
/// <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>. | |
/// Modifies tables by setting column widths to 2000 | |
/// 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 root of your project). | |
/// </param> | |
/// <param name="filename"> | |
/// The name of the Word Document file to modify (default is "WordTables.docx"). | |
/// </param> | |
/// <param name="filenameModified"> | |
/// The name of the modified Word Document (default is "ModifiedWordTables.docx"). | |
/// </param> | |
public void ModifyTablesInWordDocument(string documentDirectory = docsDirectory, | |
string filename = "WordTables.docx", string filenameModified = "ModifiedWordTables.docx") | |
{ | |
try | |
{ | |
// Load the Word Document | |
var doc = new FileFormat.Words.Document($"{documentDirectory}/{filename}"); | |
var body = new FileFormat.Words.Body(doc); | |
var tables = body.Tables; | |
foreach (var table in tables) | |
{ | |
table.Column.Width = 2000; | |
doc.Update(table); | |
} | |
// Save the modified Word Document | |
doc.Save($"{documentDirectory}/{filenameModified}"); | |
System.Console.WriteLine($"Word Document {filename} Modified and Saved As {filenameModified}. "+ | |
$"Please check directory: "+ | |
$"{System.Path.GetFullPath(documentDirectory)}"); | |
} | |
catch (System.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