Customization and Configuration
ConsoleTables provides several options to customize the appearance and behavior of your tables.
Using the Configure
Method
The most common way to apply options is through the fluent .Configure()
method, which gives you access to a ConsoleTableOptions
object.
var rows = Enumerable.Repeat(new Something(), 2);
ConsoleTable.From(rows)
.Configure(o => o.NumberAlignment = Alignment.Right)
.Write();
Configuring Options via Constructor
You can also pass a ConsoleTableOptions
object directly to the constructor. This is particularly useful for setting options before adding rows manually.
var options = new ConsoleTableOptions
{
Columns = new[] { "one", "two", "three" },
EnableCount = false
};
var noCountTable = new ConsoleTable(options);
noCountTable.AddRow(1, 2, 3).Write();
Available Options
Number Alignment
By default, all columns are left-aligned. You can right-align numeric types when creating a table from a collection of objects (From<T>
).
o.NumberAlignment = Alignment.Right
public class User { public string Name { get; set; } public int Age { get; set; } }
var users = new List<User> { new User { Name = "Alexandre", Age = 36 } };
// Default (Left-aligned)
ConsoleTable.From(users).Write();
// Right-aligned numbers
ConsoleTable.From(users)
.Configure(o => o.NumberAlignment = Alignment.Right)
.Write();
Output (Right-aligned):
-------------------
| Name | Age |
-------------------
| Alexandre | 36 |
-------------------
Count: 1
Disabling the Row Count
To remove the Count: X
footer from the output, set EnableCount
to false
.
o.EnableCount = false
var table = new ConsoleTable("A", "B");
table.AddRow(1, 2)
.Configure(o => o.EnableCount = false)
.Write();
Output:
-------
| A | B |
-------
| 1 | 2 |
-------
Width and Word Breaking
For cells containing long strings, ConsoleTables can automatically wrap the text to fit within a specified maximum width.
table.MaxWidth = 40;
: Sets the maximum character width for any single cell before wrapping occurs. The default is40
.table.SetWordBreakDelimiter(' ');
: Sets the character to use for word breaking. The default is a space.
var table = new ConsoleTable("Column A", "Column B");
table.MaxWidth = 15;
table.AddRow("This is a very long sentence that needs to be wrapped.", "Short");
table.Write();
Custom Output Target
By default, table.Write()
outputs to Console.Out
. You can redirect this to any System.IO.TextWriter
, such as a StringWriter
or a file stream.
o.OutputTo = myTextWriter;
This is useful for capturing table output as a string or for logging.
using System.IO;
var testWriter = new StringWriter();
var table = new ConsoleTable("Data");
table.AddRow("Hello")
.Configure(o => o.OutputTo = testWriter)
.Write();
string tableAsString = testWriter.ToString();
// Now tableAsString contains the full formatted table text.