Skip to content

Instantly share code, notes, and snippets.

@fileformat-words-gists
Last active December 21, 2023 01:27
Show Gist options
  • Save fileformat-words-gists/c05f8f128080801fff348a41e38d0364 to your computer and use it in GitHub Desktop.
Save fileformat-words-gists/c05f8f128080801fff348a41e38d0364 to your computer and use it in GitHub Desktop.
C# Create Word Document Tables
/// <summary>
/// Creates a new Word Document with structured content using
/// <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>.
/// Generates 5(rows) x 3(cols) tables with table styles defined by the Word document template.
/// Appends each table to the body of the word document.
/// Saves the newly created word document.
/// </summary>
/// <param name="documentDirectory">
/// The directory where the Word Document will be saved (default is root of your project).
/// </param>
/// <param name="filename">
/// The name of the Word Document file (default is "WordTables.docx").
/// </param>
public void CreateWordDocumentWithTables(string documentDirectory = "../../../",
string filename = "WordTables.docx")
{
try
{
// Initialize a new word document with the default template
var doc = new FileFormat.Words.Document();
System.Console.WriteLine("Word Document with default template initialized");
// Initialize the body with the new document
var body = new FileFormat.Words.Body(doc);
System.Console.WriteLine("Body of the Word Document initialized");
// Get all table styles
var tableStyles = doc.GetElementStyles().TableStyles;
System.Console.WriteLine("Table styles loaded");
// Create Headings Paragraph and append to the body.
foreach (var tableStyle in tableStyles)
{
var table = new FileFormat.Words.IElements.Table(5,3);
table.Style = tableStyle;
table.Column.Width = 2500;
var rowNumber = 0;
var columnNumber = 0;
var para = new FileFormat.Words.IElements.Paragraph();
para.Style = FileFormat.Words.IElements.Headings.Heading1;
para.AddRun(new FileFormat.Words.IElements.Run {
Text = $"Table With Style '{tableStyle}' : "
});
body.AppendChild(para);
foreach (var row in table.Rows)
{
rowNumber++;
foreach(var cell in row.Cells)
{
columnNumber++;
para = new FileFormat.Words.IElements.Paragraph();
para.AddRun(new FileFormat.Words.IElements.Run {
Text = $"Row {rowNumber} Column {columnNumber}"
});
cell.Paragraphs.Add(para);
}
columnNumber = 0;
}
body.AppendChild(table);
System.Console.WriteLine($"Table with style {tableStyle} created and appended");
}
// Save the newly created Word Document.
doc.Save($"{documentDirectory}/{filename}");
System.Console.WriteLine($"Word Document {filename} Created. Please check directory: "+
$"{System.IO.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