### New Table Initialization (v1.0.x) - Minimal Setup Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Shows the basic initialization of a tablewriter using `NewTable` with default configurations. This is the simplest way to start using the updated API. ```go package main import ( "fmt" // Added for FormattableEntry example "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/renderer" // Import renderer "github.com/olekukonko/tablewriter/tw" "os" "strings" // Added for Formatter example ) func main() { // Minimal Setup (Default Configuration) tableMinimal := tablewriter.NewTable(os.Stdout) _ = tableMinimal // Avoid "declared but not used" ``` -------------------------------- ### Install Tablewriter CLI Tool Source: https://github.com/olekukonko/tablewriter/blob/master/cmd/csv2table/README.md Install the tablewriter command-line tool using go install. Ensure your Go environment is set up correctly. ```bash go install github.com/olekukonko/tablewriter/cmd/csv2table@latest ``` -------------------------------- ### Minimal Table Setup in Go Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md A basic table with default settings. Uses default renderer and configuration. Replaces v0.0.5's NewWriter and SetHeader/Append. ```go package main import ( "github.com/olekukonko/tablewriter" "os" ) func main() { table := tablewriter.NewTable(os.Stdout) table.Header("Name", "Status") ttable.Append("Node1", "Ready") ttable.Render() } ``` -------------------------------- ### Render Table Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Use `Render()` to render the table and get an error. For streaming, use `Start()` and `Close()`. ```go err := table.Render() // or for streaming table.Start() // ... write rows ... table.Close() // deprecated table.Render() ``` -------------------------------- ### Quick Example of TableWriter Usage Source: https://github.com/olekukonko/tablewriter/blob/master/README.md This Go code demonstrates how to create and render a simple table with a header and data rows using TableWriter. Ensure you import the necessary packages and handle potential errors. ```go package main import ( "github.com/olekukonko/tablewriter" "os" ) func main() { data := [][]string{ {"Package", "Version", "Status"}, {"tablewriter", "v0.0.5", "legacy"}, {"tablewriter", "v1.1.4", "latest"}, } table := tablewriter.NewWriter(os.Stdout) ttable.Header(data[0]) ttable.Bulk(data[1:]) ttable.Render() } ``` -------------------------------- ### Implement HTML Renderer for TableWriter Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Implement the `tw.Renderer` interface to create a custom HTML table output. This example shows how to handle table start, headers, rows, and closing tags. ```go package main import ( "fmt" "github.com/olekukonko/ll" // For logger type "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" "io" "os" ) // BasicHTMLRenderer implements tw.Renderer type BasicHTMLRenderer struct { writer io.Writer config tw.Rendition // Store the rendition logger *ll.Logger err error } func (r *BasicHTMLRenderer) Start(w io.Writer) error { r.writer = w _, r.err = r.writer.Write([]byte("\n")) return r.err } // Header expects [][]string for potentially multi-line headers func (r *BasicHTMLRenderer) Header(headers [][]string, ctx tw.Formatting) { if r.err != nil { return } _, r.err = r.writer.Write([]byte(" \n")) if r.err != nil { return } // Iterate over cells from the context for the current line for _, cellCtx := range ctx.Row.Current { content := fmt.Sprintf(" \n", cellCtx.Data) _, r.err = r.writer.Write([]byte(content)) if r.err != nil { return } } _, r.err = r.writer.Write([]byte(" \n")) } // Row expects []string for a single line row, but uses ctx for actual data func (r *BasicHTMLRenderer) Row(row []string, ctx tw.Formatting) { // row param is less relevant here, ctx.Row.Current is key if r.err != nil { return } _, r.err = r.writer.Write([]byte(" \n")) if r.err != nil { return } for _, cellCtx := range ctx.Row.Current { content := fmt.Sprintf(" \n", cellCtx.Data) _, r.err = r.writer.Write([]byte(content)) if r.err != nil { return } } _, r.err = r.writer.Write([]byte(" \n")) } func (r *BasicHTMLRenderer) Footer(footers [][]string, ctx tw.Formatting) { if r.err != nil { return } // Similar to Header/Row, using ctx.Row.Current for the footer line data // The footers [][]string param might be used if the renderer needs multi-line footer logic r.Row(nil, ctx) // Reusing Row logic, passing nil for the direct row []string as ctx contains the data } func (r *BasicHTMLRenderer) Line(ctx tw.Formatting) { /* No lines in basic HTML */ } func (r *BasicHTMLRenderer) Close() error { if r.err != nil { return r.err } _, r.err = r.writer.Write([]byte("
%s
%s
\n")) return r.err } func (r *BasicHTMLRenderer) Config() tw.Rendition { return r.config } func (r *BasicHTMLRenderer) Logger(logger *ll.Logger) { r.logger = logger } func main() { table := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(&BasicHTMLRenderer{ config: tw.Rendition{Symbols: tw.NewSymbols(tw.StyleASCII)}, // Provide a default Rendition })) table.Header("Name", "Status") table.Append("Node1", "Ready") table.Render() } ``` -------------------------------- ### Tablewriter v0.0.5 Color Example (Mock) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md This is a mock representation of how colors might have been applied in v0.0.5 using specific color-setting methods. Actual v0.0.5 definitions are not provided. ```go package main // Assuming tablewriter.Colors and color constants existed in v0.0.5 // This is a mock representation as the actual v0.0.5 definitions are not provided. // import "github.com/olekukonko/tablewriter" // import "os" // type Colors []interface{} // Mock // const ( // Bold = 1; FgGreenColor = 2; FgRedColor = 3 // Mock constants // ) func main() { // table := tablewriter.NewWriter(os.Stdout) // table.SetColumnColor( // tablewriter.Colors{tablewriter.Bold, tablewriter.FgGreenColor}, // Column 0 // tablewriter.Colors{tablewriter.FgRedColor}, // Column 1 // ) // table.SetHeader([]string{"Name", "Status"}) // table.Append([]string{"Node1", "Ready"}) // table.Render() } ``` -------------------------------- ### Install Stable Version of Tablewriter Source: https://github.com/olekukonko/tablewriter/blob/master/README_LEGACY.md Use this command to install the stable v0.0.5 version for production use. ```bash go get github.com/olekukonko/tablewriter@v0.0.5 ``` -------------------------------- ### Build Table Configuration with ConfigBuilder Source: https://context7.com/olekukonko/tablewriter/llms.txt Use the ConfigBuilder fluent API to construct complex table configurations programmatically. This example shows how to set maximum width, trim spaces, auto-hide columns, and configure header, row, footer, and behavior settings. ```go package main import ( "os" "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" ) func main() { // Build configuration using fluent API config := tablewriter.NewConfigBuilder(). WithMaxWidth(100). WithTrimSpace(tw.On). WithAutoHide(tw.Off). // Configure header Header(). Alignment().WithGlobal(tw.AlignCenter).Build(). Formatting().WithAutoFormat(tw.On).WithAutoWrap(tw.WrapTruncate).Build(). Padding().WithGlobal(tw.Padding{Left: " ", Right: " "}).Build(). Build(). // Configure rows Row(). Alignment().WithGlobal(tw.AlignLeft).Build(). Formatting().WithAutoWrap(tw.WrapNormal).Build(). Merging().WithMode(tw.MergeVertical).Build(). Build(). // Configure footer Footer(). Alignment().WithGlobal(tw.AlignRight).Build(). Build(). // Configure behavior Behavior(). WithHeaderHide(tw.Off). WithFooterHide(tw.Off). WithAutoHeader(tw.On). Build(). Build() table := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(config)) table.Header([]string{"Department", "Team", "Lead", "Budget"}) table.Bulk([][]string{ {"Engineering", "Backend", "Alice", "$500K"}, {"Engineering", "Frontend", "Bob", "$400K"}, {"Marketing", "Digital", "Charlie", "$300K"}, }) table.Footer([]string{"", "", "Total", "$1.2M"}) table.Render() } ``` -------------------------------- ### Tablewriter v0.0.5 Stringer Example (Commented Out) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md This is a commented-out example from v0.0.5 demonstrating the basic usage of fmt.Stringer for custom types before enhanced stringer support was introduced. ```go package main // v0.0.5 primarily relied on fmt.Stringer for custom types. // import "fmt" // import "github.com/olekukonko/tablewriter" // import "os" // type MyCustomType struct { // Value string // } // func (m MyCustomType) String() string { return "Formatted: " + m.Value } func main() { // table := tablewriter.NewWriter(os.Stdout) // table.SetHeader([]string{"Custom Data"}) // table.Append([]string{MyCustomType{"test"}.String()}) // Manual call to String() // table.Render() } ``` -------------------------------- ### Install Development Version of Tablewriter Source: https://github.com/olekukonko/tablewriter/blob/master/README_LEGACY.md Use this command to install the latest development version from the master branch. This version is unstable. ```bash go get github.com/olekukonko/tablewriter@master ``` -------------------------------- ### Create Table with NewConfigBuilder Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Use `NewConfigBuilder` for a fluent API to construct `Config` objects, simplifying complex table setups. ```go builder := tablewriter.NewConfigBuilder() cfg := builder.Build() table := tablewriter.NewTable(os.Stdout, cfg) ``` -------------------------------- ### Install TableWriter Latest Version Source: https://github.com/olekukonko/tablewriter/blob/master/README.md Use this command to install the latest stable version of TableWriter, which includes new features like generics and streaming APIs. ```bash go get github.com/olekukonko/tablewriter@v1.1.4 ``` -------------------------------- ### Setting Footers (New Method - Variadic) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Illustrates the new `Footer(...any)` method in tablewriter v1.0.x, which accepts variadic arguments for flexible footer input. This example shows setting a simple footer with a string and an integer. ```go package main import ( "fmt" "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" // For tw.Formatter os ) // Using Formatter type FooterSummary struct { // Renamed to avoid conflict Label string Value float64 } func (s FooterSummary) Format() string { return fmt.Sprintf("%s: %.2f", s.Label, s.Value) } // Implements tw.Formatter func main() { table := tablewriter.NewTable(os.Stdout) table.Header("ColA", "ColB", "ColC", "ColD") // Header for context // Variadic Arguments table.Footer("", "", "Total", 1408) // Slice of Any Type // table.Footer([]any{"", "", "Total", 1408.50}) table.Render() // Render this table fmt.Println("---") table2 := tablewriter.NewTable(os.Stdout) ttable2.Header("Summary Info") // Single column header // Using Formatter for a single cell footer ttable2.Footer(FooterSummary{Label: "Grand Total", Value: 1408.50}) // Single cell: "Grand Total: 1408.50" ttable2.Render() } ``` -------------------------------- ### Global Filter Example (New) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Applies a transformation to all cells within the 'Row' section. This example wraps all cell content in brackets. ```go // Global filter example (applied to all cells in the Row section) cfgGlobalFilter := tablewriter.NewConfigBuilder() cfgGlobalFilter.Row().Filter().WithGlobal(func(s string) string { return "[" + s + "]" // Wrap all row cells in brackets }) tableGlobalFilter := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfgGlobalFilter.Build())) tableGlobalFilter.Header("Item", "Count") tableGlobalFilter.Append("Apple", "5") tableGlobalFilter.Render() } ``` -------------------------------- ### Initialize Tablewriter Configuration Builder Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Use `NewConfigBuilder()` to start creating a new tablewriter configuration. This method is the entry point for the fluent builder pattern in v1.0.x. ```go config.go:NewConfigBuilder ``` -------------------------------- ### Streaming Table with Fixed Widths in Go Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Demonstrates streaming mode for real-time data output with fixed column widths. Requires Start() and Close() calls. Ensure error handling for streaming operations. ```go package main import ( "fmt" "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" "log" "os" ) func main() { table := tablewriter.NewTable(os.Stdout, tablewriter.WithStreaming(tw.StreamConfig{Enable: true}), tablewriter.WithColumnMax(10), // Sets Config.Widths.Global ) if err := table.Start(); err != nil { log.Fatalf("Start failed: %v", err) } table.Header("Name", "Status") for i := 0; i < 2; i++ { err := table.Append(fmt.Sprintf("Node%d", i+1), "Ready") if err != nil { log.Printf("Append failed: %v", err) } } if err := table.Close(); err != nil { log.Fatalf("Close failed: %v", err) } } ``` -------------------------------- ### Use Custom Renderers for Different Output Formats Source: https://context7.com/olekukonko/tablewriter/llms.txt Generate tables in various formats like Markdown or SVG using different renderers. This example shows how to use the Blueprint renderer with custom symbols and the Markdown renderer. ```go package main import ( "os" "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/renderer" "github.com/olekukonko/tablewriter/tw" ) func main() { data := [][]string{ {"Alice", "30", "Engineer"}, {"Bob", "25", "Designer"}, } // Default Blueprint renderer with custom symbols table := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(renderer.NewBlueprint(tw.Rendition{ Symbols: tw.NewSymbols(tw.StyleDouble), // Double-line borders })), ) table.Header([]string{"Name", "Age", "Role"}) table.Bulk(data) table.Render() // Markdown renderer mdTable := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(renderer.NewMarkdown()), ) mdTable.Header([]string{"Name", "Age", "Role"}) mdTable.Bulk(data) mdTable.Render() // Output: // | Name | Age | Role | // |-------|-----|----------| // | Alice | 30 | Engineer | // | Bob | 25 | Designer | } ``` -------------------------------- ### Basic Table Creation in Go Source: https://github.com/olekukonko/tablewriter/blob/master/README_LEGACY.md Demonstrates how to create a basic table with headers and data, then render it to standard output. ```go data := [][]string{ []string{"A", "The Good", "500"}, []string{"B", "The Very very Bad Man", "288"}, []string{"C", "The Ugly", "120"}, []string{"D", "The Gopher", "800"}, } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Name", "Sign", "Rating"}) for _, v := range data { table.Append(v) } table.Render() // Send output ``` -------------------------------- ### Create Basic Table with Header and Data Source: https://github.com/olekukonko/tablewriter/blob/master/README.md Demonstrates creating a simple table with headers and rows using NewTable, Header, Bulk, and Render. Ensure os and fmt packages are imported. ```go package main import ( "fmt" "github.com/olekukonko/tablewriter" "os" ) type Age int func (a Age) String() string { return fmt.Sprintf("%d yrs", a) } func main() { data := [][]any{ {"Alice", Age(25), "New York"}, {"Bob", Age(30), "Boston"}, } table := tablewriter.NewTable(os.Stdout) ttable.Header("Name", "Age", "City") ttable.Bulk(data) ttable.Render() } ``` -------------------------------- ### Create and Render Basic Table Source: https://context7.com/olekukonko/tablewriter/llms.txt Demonstrates creating a basic table writer instance, setting headers, appending rows individually, and rendering the table to standard output. ```go package main import ( "os" "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" ) func main() { // Create a basic table writing to stdout table := tablewriter.NewTable(os.Stdout) // Set headers table.Header([]string{"Name", "Age", "City"}) // Add rows individually table.Append([]string{"Alice", "30", "New York"}) table.Append([]string{"Bob", "25", "San Francisco"}) table.Append([]string{"Charlie", "35", "Chicago"}) // Render the table table.Render() // Output: // +----------+-----+---------------+ // | NAME | AGE | CITY | // +----------+-----+---------------+ // | Alice | 30 | New York | // | Bob | 25 | San Francisco | // | Charlie | 35 | Chicago | // +----------+-----+---------------+ } ``` -------------------------------- ### Configure Standard Bordered Table (v1.0.x) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Illustrates setting up a standard bordered table with internal lines using `tw.Rendition` fields in v1.0.x. This approach offers granular control over borders and separators. ```go package main import ( "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/renderer" "github.com/olekukonko/tablewriter/tw" "os" ) func main() { // Standard Bordered Table with Internal Lines table := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(renderer.NewBlueprint()), tablewriter.WithRendition(tw.Rendition{ Borders: tw.Border{ // Outer table borders Left: tw.On, Right: tw.On, Top: tw.On, Bottom: tw.On, }, Settings: tw.Settings{ Lines: tw.Lines{ // Major internal separator lines ShowHeaderLine: tw.On, // Line after header ShowFooterLine: tw.On, // Line before footer (if footer exists) }, Separators: tw.Separators{ BetweenRows: tw.On, // Horizontal lines between data rows BetweenColumns: tw.On, // Vertical lines between columns }, }, }), ) table.Header("Name", "Status") table.Append("Node1", "Ready") ttable.Render() // Borderless Table (kubectl-style, No Lines or Separators) // Configure the table with a borderless, kubectl-style layout config := tablewriter.NewConfigBuilder(). Header(). Padding(). WithGlobal(tw.PaddingNone). // No header padding Build(). Alignment(). WithGlobal(tw.AlignLeft). // Left-align header Build(). Row(). Padding(). WithGlobal(tw.PaddingNone). // No row padding Build(). Alignment(). WithGlobal(tw.AlignLeft). // Left-align rows Build(). Footer(). Padding(). WithGlobal(tw.PaddingNone). // No footer padding Build(). Alignment(). WithGlobal(tw.AlignLeft). // Left-align footer (if used) Build(). WithDebug(true). // Enable debug logging Build() // Create borderless table tableBorderless := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(renderer.NewBlueprint()), // Assumes valid renderer tablewriter.WithRendition(tw.Rendition{ Borders: tw.BorderNone, // No borders Symbols: tw.NewSymbols(tw.StyleNone), // No border symbols Settings: tw.Settings{ Lines: tw.LinesNone, // No header/footer lines Separators: tw.SeparatorsNone, // No row/column separators }, }), tablewriter.WithConfig(config), ) // Set headers and data tableBorderless.Header("Name", "Status") tableBorderless.Append("Node1", "Ready") ttableBorderless.Render() } ``` -------------------------------- ### New Table Initialization with ConfigBuilder Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Demonstrates the fluent API of `ConfigBuilder` for constructing complex table configurations. This method allows for a more readable and chainable way to set various table properties. ```go // Using ConfigBuilder for Fluent, Complex Configuration builder := tablewriter.NewConfigBuilder(). WithMaxWidth(80). WithAutoHide(tw.Off). WithTrimSpace(tw.On). WithDebug(true). // Enable debug logging Header(). Alignment(). WithGlobal(tw.AlignCenter). Build(). // Returns *ConfigBuilder Header(). Formatting(). WithAutoFormat(tw.On). WithAutoWrap(tw.WrapTruncate). // Test truncation WithMergeMode(tw.MergeNone). // Explicit merge mode Build(). // Returns *HeaderConfigBuilder Padding(). WithGlobal(tw.Padding{Left: "[", Right: "]", Overwrite: true}). Build(). // Returns *HeaderConfigBuilder Build(). // Returns *ConfigBuilder Row(). Formatting(). WithAutoFormat(tw.On). // Uppercase rows Build(). // Returns *RowConfigBuilder Build(). // Returns *ConfigBuilder Row(). Alignment(). WithGlobal(tw.AlignLeft). Build(). // Returns *ConfigBuilder Build() // Finalize Config tableWithFluent := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(builder)) _ = tableWithFluent // Avoid "declared but not used" } ``` -------------------------------- ### Configure Table with Standalone Option Functions Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Use WithXxx functions (e.g., WithHeaderAlignment, WithDebug) during NewTable initialization. Best for simple, specific configuration changes without needing a full Config struct. ```go package main import ( "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" "os" ) func main() { table := tablewriter.NewTable(os.Stdout, tablewriter.WithHeaderAlignment(tw.AlignCenter), tablewriter.WithRowAlignment(tw.AlignLeft), tablewriter.WithDebug(true), ) table.Header("Name", "Status") table.Append("Node1", "Ready") table.Render() } ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Use `WithDebug(true)` and `table.Debug()` to log configuration and rendering details. This is invaluable for troubleshooting. ```go config.go ``` -------------------------------- ### Example SVG Table Output Source: https://github.com/olekukonko/tablewriter/blob/master/README.md This is an example of the SVG output generated by the tablewriter library. It defines rectangles and text elements to represent the table structure and content. ```svg NAME AGE CITY Alice 25 yrs New York Bob 30 yrs Boston ``` -------------------------------- ### Tablewriter tw.Formatter Example Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md This example shows how to use the `tw.Formatter` interface for custom types. Types implementing `Format() string` will use this method for their string representation, which is checked before `fmt.Stringer`. ```go package main import ( "fmt" "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" "os" "strings" ) // Example 1: Using WithStringer for general conversion type CustomInt int func main() { // Table with a general stringer (func(any) []string) tableWithStringer := tablewriter.NewTable(os.Stdout, tablewriter.WithStringer(func(v any) []string { // Must return []string if ci, ok := v.(CustomInt); ok { return []string{fmt.Sprintf("CustomInt Value: %d!", ci)} } return []string{fmt.Sprintf("Value: %v", v)} // Fallback }), tablewriter.WithDebug(true), // Enable caching if WithStringerCache() is also used // tablewriter.WithStringerCache(), // Optional: enable caching ) ttableWithStringer.Header("Data") ttableWithStringer.Append(123) ttableWithStringer.Append(CustomInt(456)) ttableWithStringer.Render() fmt.Println("\n--- Table with Type-Specific Stringer for Structs ---") // Example 2: Stringer for a specific struct type type Person struct { ID int Name string City string } // Stringer for Person to produce 3 cells personToStrings := func(p Person) []string { return []string{ fmt.Sprintf("ID: %d", p.ID), p.Name, strings.ToUpper(p.City), } } tablePersonStringer := tablewriter.NewTable(os.Stdout, tablewriter.WithStringer(personToStrings), // Pass the type-specific function ) ttablePersonStringer.Header("User ID", "Full Name", "Location") ttablePersonStringer.Append(Person{1, "Alice", "New York"}) ttablePersonStringer.Append(Person{2, "Bob", "London"}) ttablePersonStringer.Render() fmt.Println("\n--- Table with tw.Formatter ---") // Example 3: Using tw.Formatter for types type Product struct { Name string Price float64 } func (p Product) Format() string { // Implements tw.Formatter return fmt.Sprintf("%s - $%.2f", p.Name, p.Price) } ttableFormatter := tablewriter.NewTable(os.Stdout) ttableFormatter.Header("Product Details") ttableFormatter.Append(Product{"Laptop", 1200.99}) // Will use Format() ttableFormatter.Render() } ``` -------------------------------- ### Configuring Table Appearance and Behavior Source: https://context7.com/olekukonko/tablewriter/llms.txt Illustrates how to configure table appearance using functional parameters for alignment, text wrapping, maximum widths, whitespace trimming, and other behaviors. ```go package main import ( "os" "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" ) func main() { table := tablewriter.NewTable(os.Stdout, // Set column alignments tablewriter.WithHeaderAlignment(tw.AlignCenter), tablewriter.WithRowAlignment(tw.AlignLeft), tablewriter.WithFooterAlignment(tw.AlignRight), // Configure text wrapping tablewriter.WithRowAutoWrap(tw.WrapNormal), // Standard word wrap tablewriter.WithHeaderAutoWrap(tw.WrapTruncate), // Truncate with ellipsis // Set maximum widths tablewriter.WithMaxWidth(80), // Max table width tablewriter.WithRowMaxWidth(20), // Max content width per cell // Control whitespace tablewriter.WithTrimSpace(tw.On), tablewriter.WithTrimTab(tw.On), // Auto-hide empty columns tablewriter.WithAutoHide(tw.On), // Enable debug logging tablewriter.WithDebug(true), ) table.Header([]string{"Name", "Description", "Status"}) table.Append([]string{"Widget", "A useful widget for processing data efficiently", "Active"}) table.Append([]string{"Gadget", "Compact device", "Inactive"}) table.Footer([]string{"", "Total Items", "2"}) table.Render() } ``` -------------------------------- ### Streaming Table Operations Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Manage row-by-row rendering using `Start()`, `Append()`, and `Close()` for streaming data. ```go err := table.Start() // ... err = table.Append(row) // ... err = table.Close() ``` -------------------------------- ### Initialize Table Writer Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Use `NewTable` with a writer and options. `NewWriter` is deprecated and wraps `NewTable`. ```go table := tablewriter.NewTable(writer) // or with options table := tablewriter.NewTable(writer, tablewriter.WithBorder()) // or deprecated table := tablewriter.NewWriter(writer) ``` -------------------------------- ### Old Tablewriter Rendering (v0.0.5) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Example of rendering a table using the older version of tablewriter. This version uses Render() without explicit error handling. ```go package main import ( "github.com/olekukonko/tablewriter" "os" ) func main() { table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Data"}) ttable.Append([]string{"Example"}) ttable.Render() } ``` -------------------------------- ### New Table Initialization with Option Functions Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Illustrates configuring a tablewriter instance using variadic `Option` functions passed to `NewTable`. This approach allows for targeted modifications to specific settings like header and row alignment. ```go // Using Option Functions for Targeted Configuration tableWithOptions := tablewriter.NewTable(os.Stdout, tablewriter.WithHeaderAlignment(tw.AlignCenter), // Center header text tablewriter.WithRowAlignment(tw.AlignLeft), // Left-align row text tablewriter.WithDebug(true), // Enable debug logging ) _ = tableWithOptions // Avoid "declared but not used" ``` -------------------------------- ### Set Table Headers (v0.0.5) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Example of setting string headers using the older `SetHeader` method in tablewriter v0.0.5. This method only accepts a slice of strings. ```go package main import ( "github.com/olekukonko/tablewriter" "os" ) func main() { table := tablewriter.NewWriter(os.Stdout) t.SetHeader([]string{"Name", "Sign", "Rating"}) // ... } ``` -------------------------------- ### Configure Text Wrapping with Options (v1.0.x) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Shows how to configure text wrapping using option functions for rows, headers, and footers, along with setting a maximum table width. Requires 'os', 'tablewriter', and 'tablewriter/tw' packages. ```go package main import ( "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" // For tw.WrapNormal etc. "os" ) func main() { // Using Option Functions for Quick Wrapping Settings on a specific section (e.g., Row) // To actually see wrapping, a MaxWidth for the table or columns is needed. table := tablewriter.NewTable(os.Stdout, tablewriter.WithRowAutoWrap(tw.WrapNormal), // Set row wrapping tablewriter.WithHeaderAutoWrap(tw.WrapTruncate), // Header truncates (default) tablewriter.WithMaxWidth(30), // Force wrapping by setting table max width ) table.Header("Long Header Text", "Status") table.Append("This is a very long cell content", "Ready") table.Footer("Summary", "Active") table.Render() // For more fine-grained control (e.g., different wrapping for header, row, footer): cfgBuilder := tablewriter.NewConfigBuilder() cfgBuilder.Header().Formatting().WithAutoWrap(tw.WrapTruncate) // Header: Truncate cfgBuilder.Row().Formatting().WithAutoWrap(tw.WrapNormal) // Row: Normal wrap cfgBuilder.Footer().Formatting().WithAutoWrap(tw.WrapBreak) // Footer: Break words cfgBuilder.WithMaxWidth(40) // Overall table width constraint tableFullCfg := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfgBuilder.Build())) tableFullCfg.Header("Another Very Long Header Example That Will Be Truncated", "Info") tableFullCfg.Append("This is an example of row content that should wrap normally based on available space.", "Detail") tableFullCfg.Footer("FinalSummaryInformationThatMightBreakAcrossLines", "End") tableFullCfg.Render() } ``` -------------------------------- ### Tablewriter Streaming API Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Utilize the `Start()`, `Append()`, and `Close()` methods for true streaming support, enabling incremental rendering suitable for large or real-time datasets. ```go stream.go ``` -------------------------------- ### Reading and Rendering CSV Data in Go Source: https://github.com/olekukonko/tablewriter/blob/master/README_LEGACY.md Demonstrates how to create a table directly from a CSV file, setting the alignment to left. Assumes a CSV file named 'test_info.csv' exists. ```go table, _ := tablewriter.NewCSV(os.Stdout, "testdata/test_info.csv", true) table.SetAlignment(tablewriter.ALIGN_LEFT) // Set Alignment table.Render() ``` -------------------------------- ### Tablewriter v0.0.5 Data Preprocessing (Old) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md In older versions, data preprocessing was manual before appending to the table. This example shows how to trim whitespace from a status string before adding it. ```go package main // No direct support for cell content transformation in v0.0.5. // Users would typically preprocess data before appending. // import "github.com/olekukonko/tablewriter" // import "os" // import "strings" func main() { // table := tablewriter.NewWriter(os.Stdout) // table.SetHeader([]string{"Name", "Status"}) // status := " Ready " // preprocessedStatus := "Status: " + strings.TrimSpace(status) // table.Append([]string{"Node1", preprocessedStatus}) // table.Render() } ``` -------------------------------- ### Use Custom Invoice Renderer with Tablewriter Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Demonstrates how to create a tablewriter instance with the custom `InvoiceRenderer` and render data. It also shows a comparison with the default renderer. ```go func main() { data := [][]string{ {"Product A", "2", "10.00", "20.00"}, {"Super Long Product Name B", "1", "125.50", "125.50"}, {"Item C", "10", "1.99", "19.90"}, } header := []string{"Description", "Qty", "Unit Price", "Total Price"} footer := []string{"", "", "Subtotal:\nTax (10%):\nGRAND TOTAL:", "165.40\n16.54\n181.94"} invoiceRenderer := NewInvoiceRenderer() // Create table and set custom renderer using Options table := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(invoiceRenderer), tablewriter.WithAlignment([]tw.Align{ tw.AlignLeft, tw.AlignCenter, tw.AlignRight, tw.AlignRight, }), ) table.Header(header) for _, v := range data { table.Append(v) } // Use the Footer method with strings containing newlines for multi-line cells table.Footer(footer) fmt.Println("Rendering with InvoiceRenderer:") table.Render() // For comparison, render with default Blueprint renderer // Re-create the table or reset it to use a different renderer table2 := tablewriter.NewTable(os.Stdout, tablewriter.WithAlignment([]tw.Align{ tw.AlignLeft, tw.AlignCenter, tw.AlignRight, tw.AlignRight, }), ) table2.Header(header) for _, v := range data { table2.Append(v) } table2.Footer(footer) fmt.Println("\nRendering with Default Blueprint Renderer (for comparison):") table2.Render() } ``` -------------------------------- ### Old Table Initialization (v0.0.5) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Demonstrates the deprecated `NewWriter` method for initializing a tablewriter instance. This method is retained for backward compatibility but `NewTable` is recommended for new development. ```go package main import ( "github.com/olekukonko/tablewriter" "os" ) func main() { table := tablewriter.NewWriter(os.Stdout) // ... use table _ = table // Avoid "declared but not used" } ``` -------------------------------- ### Streaming Width Fixing Behavior Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Column widths are locked after Start() is called in streaming mode. Providing inconsistent data after this point may lead to unexpected truncation. ```go Start() ``` -------------------------------- ### Fix Widths in Streaming Mode Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md In streaming mode, set Config.Widths before calling Start() to fix column widths. This prevents content-based sizing and ensures a consistent layout. ```go Config.Widths ``` -------------------------------- ### New Padding Configuration (v1.0.x) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Illustrates the new, granular cell padding configuration using a Config struct in v1.0.x. This allows for global, per-column, and per-side padding. ```go package main import ( "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/tw" "os" ) func main() { // Using Direct Config Struct cfg := tablewriter.Config{ Header: tw.CellConfig{ Padding: tw.CellPadding{ Global: tw.Padding{Left: "[", Right: "]", Top: "-", Bottom: "-"}, // Padding for all header cells PerColumn: []tw.Padding{ {Left: ">>", Right: "<<", Top: "=", Bottom: "="}, // Overrides Global for column 0 }, }, }, Row: tw.CellConfig{ Padding: tw.CellPadding{ Global: tw.PaddingDefault, // One space left/right for all row cells }, }, Footer: tw.CellConfig{ Padding: tw.CellPadding{ Global: tw.Padding{Top: "~", Bottom: "~"}, // Top/bottom padding for all footer cells }, }, } table := tablewriter.NewTable(os.Stdout, tablewriter.WithConfig(cfg)) table.Header("Name", "Status") // Two columns table.Append("Node1", "Ready") ttable.Footer("End", "Active") table.Render() } ``` -------------------------------- ### Create New Symbols with Predefined Style Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Use tw.NewSymbols to get predefined styles like ASCII, Markdown, or Rounded. Ensure the style constant is of type tw.BorderStyle. ```go tw.NewSymbols(tw.BorderStyle) ``` -------------------------------- ### Table Styling in v1.0.x (Predefined Style) Source: https://github.com/olekukonko/tablewriter/blob/master/MIGRATION.md Shows how to apply a predefined table style, such as `StyleRounded`, using `tw.Rendition.Symbols` and `tablewriter.WithRendition`. This method offers a cohesive and modern approach to table styling. ```go package main import ( "github.com/olekukonko/tablewriter" "github.com/olekukonko/tablewriter/renderer" "github.com/olekukonko/tablewriter/tw" "os" ) func main() { // Using a Predefined Style (Rounded Corners for Aesthetic Output) tableStyled := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(renderer.NewBlueprint()), // Ensure renderer is set tablewriter.WithRendition(tw.Rendition{ Symbols: tw.NewSymbols(tw.StyleRounded), // Predefined rounded style Borders: tw.Border{Top: tw.On, Bottom: tw.On, Left: tw.On, Right: tw.On}, Settings: tw.Settings{ Separators: tw.Separators{BetweenRows: tw.On}, // Lines between rows }, }), ) tableStyled.Header("Name", "Status") tableStyled.Append("Node1", "Ready") ttableStyled.Render() // Using Fully Custom Symbols (Mimicking v0.0.5 Custom Separators) mySymbols := tw.NewSymbolCustom("my-style"). // Fluent builder for custom symbols WithCenter("*"). // Junction of lines WithColumn("!"). // Vertical separator WithRow("="). // Horizontal separator WithTopLeft("/"). WithTopMid("-"). WithTopRight("\"). WithMidLeft("["). WithMidRight("]"). // Corrected from duplicate WithMidRight("+") // WithMidMid was not a method in SymbolCustom WithBottomLeft("\"). WithBottomMid("_"). WithBottomRight("/"). WithHeaderLeft("("). WithHeaderMid("-"). WithHeaderRight(")") // Header-specific ttableCustomSymbols := tablewriter.NewTable(os.Stdout, tablewriter.WithRenderer(renderer.NewBlueprint()), tablewriter.WithRendition(tw.Rendition{ Symbols: mySymbols, Borders: tw.Border{Top: tw.On, Bottom: tw.On, Left: tw.On, Right: tw.On}, }), ) ttableCustomSymbols.Header("Name", "Status") ttableCustomSymbols.Append("Node1", "Ready") ttableCustomSymbols.Render() } ```