Skip to content

Instantly share code, notes, and snippets.

@fileformat-words-gists
Last active December 16, 2023 17:54
Show Gist options
  • Save fileformat-words-gists/fb5d9fa3c0576b45140ee3be87405c79 to your computer and use it in GitHub Desktop.
Save fileformat-words-gists/fb5d9fa3c0576b45140ee3be87405c79 to your computer and use it in GitHub Desktop.
C# Read Word Document Tables
/// <summary>
/// Loads a Word Document with structured content using
/// <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>.
/// Traverses tables and displays associated styles as defined by the Word document template.
/// Traverses through each row and then traverses columns within the row.
/// Traverses through paragrpahs within each cell and displays paragraph plain text
/// </summary>
/// <param name="documentDirectory">
/// The directory where the Word Document to load is present
/// (default is root of your project).
/// </param>
/// <param name="filename">
/// The name of the Word Document file to load (default is "WordTables.docx").
/// </param>
public void ReadTablesInWordDocument(string documentDirectory = "../../../",
string filename = "WordTables.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;
var tableNumber = 0;
var rowNumber = 0;
var columnNumber = 0;
var paraNumber = 0;
foreach (var table in tables)
{
tableNumber++;
System.Console.WriteLine($"Table Number : {tableNumber}");
System.Console.WriteLine($"..Table Style : {table.Style}");
foreach (var row in table.Rows)
{
rowNumber++;
System.Console.WriteLine($"..Row Number : {rowNumber}");
foreach (var cell in row.Cells)
{
columnNumber++;
System.Console.WriteLine($"....Column Number : {columnNumber}");
foreach (var para in cell.Paragraphs)
{
paraNumber++;
System.Console.WriteLine($"......Paragraph Number : {paraNumber}");
System.Console.WriteLine($"......Paragraph Text : {para.Text}");
}
paraNumber = 0;
}
columnNumber = 0;
}
rowNumber = 0;
}
}
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