tablewriter

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2025 License: MIT Imports: 12 Imported by: 9,752

README

Table Writer for Go

ci Total views GoDoc

tablewriter is a powerful Go library for generating formatted text-based tables, supporting ASCII, HTML, Markdown, and colorized outputs. It is ideal for command-line tools, logs, or web applications. The prototype branch (targeting v0.2.0) introduces modern features like generics, streaming, and advanced cell merging.

Note: For legacy support (stable v0.0.5), refer to README_LEGACY.md. This README documents the main branch.

Features

  • Multiple Renderers: ASCII, Unicode, Markdown, HTML, or colorized outputs.
  • Flexible Configuration: Customize alignment, padding, wrapping, borders, and separators.
  • Cell Merging: Horizontal, vertical, and hierarchical merging for compact layouts.
  • Multiline Cells: Automatic wrapping or truncation of multiline content.
  • CSV Input: Create tables from CSV files or io.Reader streams.
  • Streaming Support: Render large datasets row-by-row with TableStream.
  • Colorized Output: Apply ANSI colors to headers, rows, footers, and borders.
  • Struct Input: Render tables from structs using custom stringer functions.
  • io.Writer Support: Write to os.Stdout, files, or strings.Builder.
  • Content Filtering: Mask sensitive data (e.g., emails, passwords).

Installation

go get github.com/olekukonko/tablewriter

Usage

Create a table with NewTable or NewWriter, configure it using options or a Config struct, add data with Append or Bulk, and render to an io.Writer. Use renderers like Blueprint (ASCII), HTML, Markdown, Colorized, or Ocean (streaming).

Examples

Basic Examples
1. Simple ASCII Table

Create a basic ASCII table with headers and rows.

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)
	table.Header([]string{"Name", "Age", "City"})
	table.Bulk(data)
	table.Render()
}

Output:

┌───────┬────────┬──────────┐
│ NAME  │  AGE   │   CITY   │
├───────┼────────┼──────────┤
│ Alice │ 25 yrs │ New York │
│ Bob   │ 30 yrs │ Boston   │
└───────┴────────┴──────────┘

2. Markdown Table

Generate a Markdown table for documentation.

package main

import (
	"fmt"
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/renderer"
	"os"
	"strings"
	"unicode"
)

type Name struct {
	First string
	Last  string
}

// this will be ignored since  Format() is present
func (n Name) String() string {
	return fmt.Sprintf("%s %s", n.First, n.Last)
}

// Note: Format() overrides String() if both exist.
func (n Name) Format() string {
	return fmt.Sprintf("%s %s", n.clean(n.First), n.clean(n.Last))
}

// clean ensures the first letter is capitalized and the rest are lowercase
func (n Name) clean(s string) string {
	s = strings.TrimSpace(strings.ToLower(s))
	words := strings.Fields(s)
	s = strings.Join(words, "")

	if s == "" {
		return s
	}
	// Capitalize the first letter
	runes := []rune(s)
	runes[0] = unicode.ToUpper(runes[0])
	return string(runes)
}

type Age int

// Age int will be ignore and string will be used
func (a Age) String() string {
	return fmt.Sprintf("%d yrs", a)
}

func main() {
	data := [][]any{
		{Name{"Al  i  CE", " Ma  SK"}, Age(25), "New York"},
		{Name{"bOb", "mar   le   y"}, Age(30), "Boston"},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewMarkdown()),
	)

	table.Header([]string{"Name", "Age", "City"})
	table.Bulk(data)
	table.Render()
}

Output:

|    NAME    |  AGE   |   CITY   |
|:----------:|:------:|:--------:|
| Alice Mask | 25 yrs | New York |
| Bob Marley | 30 yrs | Boston   |


3. CSV Input

Create a table from a CSV file with custom row alignment.

package main

import (
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/tw"
	"log"
	"os"
)

func main() {
	// Assuming "test.csv" contains: "First Name,Last Name,SSN\nJohn,Barry,123456\nKathy,Smith,687987"
	table, err := tablewriter.NewCSV(os.Stdout, "test.csv", true)
	if err != nil {
		log.Fatalf("Error: %v", err)
	}

	table.Configure(func(config *tablewriter.Config) {
		config.Row.Formatting.Alignment = tw.AlignLeft
	})
	table.Render()
}

Output:

┌────────────┬───────────┬─────────┐
│ FIRST NAME │ LAST NAME │   SSN   │
├────────────┼───────────┼─────────┤
│ John       │ Barry     │ 123456  │
│ Kathy      │ Smith     │ 687987  │
└────────────┴───────────┴─────────┘
Advanced Examples
4. Colorized Table with Long Values

Create a colorized table with wrapped long values, per-column colors, and a styled footer (inspired by TestColorizedLongValues and TestColorizedCustomColors).

package main

import (
	"github.com/fatih/color"
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/renderer"
	"github.com/olekukonko/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"1", "This is a very long description that needs wrapping for readability", "OK"},
		{"2", "Short description", "DONE"},
		{"3", "Another lengthy description requiring truncation or wrapping", "ERROR"},
	}

	// Configure colors: green headers, cyan/magenta rows, yellow footer
	colorCfg := renderer.ColorizedConfig{
		Header: renderer.Tint{
			FG: renderer.Colors{color.FgGreen, color.Bold}, // Green bold headers
			BG: renderer.Colors{color.BgHiWhite},
		},
		Column: renderer.Tint{
			FG: renderer.Colors{color.FgCyan}, // Default cyan for rows
			Columns: []renderer.Tint{
				{FG: renderer.Colors{color.FgMagenta}}, // Magenta for column 0
				{},                                     // Inherit default (cyan)
				{FG: renderer.Colors{color.FgHiRed}},   // High-intensity red for column 2
			},
		},
		Footer: renderer.Tint{
			FG: renderer.Colors{color.FgYellow, color.Bold}, // Yellow bold footer
			Columns: []renderer.Tint{
				{},                                      // Inherit default
				{FG: renderer.Colors{color.FgHiYellow}}, // High-intensity yellow for column 1
				{},                                      // Inherit default
			},
		},
		Border:    renderer.Tint{FG: renderer.Colors{color.FgWhite}}, // White borders
		Separator: renderer.Tint{FG: renderer.Colors{color.FgWhite}}, // White separators
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewColorized(colorCfg)),
		tablewriter.WithConfig(tablewriter.Config{
			Row: tw.CellConfig{
				Formatting: tw.CellFormatting{
					MaxWidth:  25,            // Limit column width
					AutoWrap:  tw.WrapNormal, // Wrap long content
					Alignment: tw.AlignLeft,  // Left-align rows
				},
			},
			Footer: tw.CellConfig{
				Formatting: tw.CellFormatting{Alignment: tw.AlignRight},
			},
		}),
	)

	table.Header([]string{"ID", "Description", "Status"})
	table.Bulk(data)
	table.Footer([]string{"", "Total", "3"})
	table.Render()
}

Output (colors visible in ANSI-compatible terminals):

Colorized Table with Long Values

5. Streaming Table with Truncation

Stream a table incrementally with truncation and a footer, simulating a real-time data feed (inspired by TestOceanStreamTruncation and TestOceanStreamSlowOutput).

package main

import (
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/streamer"
	"github.com/olekukonko/tablewriter/tw"
	"log"
	"os"
	"time"
)

func main() {
	// Configure Ocean streamer with fixed widths
	oceanCfg := streamer.OceanConfig{
		ColumnWidths:   []int{4, 15, 8}, // ID: 4, Desc: 15, Status: 8
		ColumnAligns:   []tw.Align{tw.AlignCenter, tw.AlignLeft, tw.AlignRight},
		HeaderAlign:    tw.AlignCenter,
		FooterAlign:    tw.AlignRight,
		ShowHeaderLine: true,
		ShowFooterLine: true,
	}

	// Create streamer
	oceanRenderer, err := streamer.NewOcean(os.Stdout, false, oceanCfg)
	if err != nil {
		log.Fatalf("Failed to create renderer: %v", err)
	}
	tableStream, err := tablewriter.NewStreamTable(os.Stdout, oceanRenderer)
	if err != nil {
		log.Fatalf("Failed to create TableStream: %v", err)
	}

	// Start streaming
	if err := tableStream.Start(); err != nil {
		log.Fatalf("Start failed: %v", err)
	}

	// Stream header
	tableStream.Header([]string{"ID", "Description", "Status"})

	// Stream rows with simulated delay
	data := [][]string{
		{"1", "This description is too long", "OK"},
		{"2", "Short desc", "DONE"},
		{"3", "Another long description here", "ERROR"},
	}
	for i, row := range data {
		if err := tableStream.Row(row); err != nil {
			log.Fatalf("Row %d failed: %v", i+1, err)
		}
		time.Sleep(500 * time.Millisecond) // Simulate real-time data feed
	}

	// Stream footer
	tableStream.Footer([]string{"", "Total", "3"})

	// End streaming
	if err := tableStream.End(); err != nil {
		log.Fatalf("End failed: %v", err)
	}
}

Output (appears incrementally):

┌────┬───────────────┬────────┐
│ ID │  DESCRIPTION  │ STATUS │
├────┼───────────────┼────────┤
│ 1  │ This descri…  │     OK │
│ 2  │ Short desc    │   DONE │
│ 3  │ Another lon…  │  ERROR │
├────┼───────────────┼────────┤
│    │         Total │      3 │
└────┴───────────────┴────────┘

Note: Long descriptions are truncated with due to fixed column widths. The output appears row-by-row, simulating a real-time feed.

6. Hierarchical Merging for Organizational Data

Show hierarchical merging for a tree-like structure, such as an organizational hierarchy (inspired by TestMergeHierarchicalUnicode).

package main

import (
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/renderer"
	"github.com/olekukonko/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"Engineering", "Backend", "API Team", "Alice"},
		{"Engineering", "Backend", "Database Team", "Bob"},
		{"Engineering", "Frontend", "UI Team", "Charlie"},
		{"Marketing", "Digital", "SEO Team", "Dave"},
		{"Marketing", "Digital", "Content Team", "Eve"},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.RendererConfig{
			Settings: tw.Settings{
				Separators: tw.Separators{BetweenRows: tw.On},
			},
		})),
		tablewriter.WithConfig(tablewriter.Config{
			Header: tw.CellConfig{
				Formatting: tw.CellFormatting{Alignment: tw.AlignCenter},
			},
			Row: tw.CellConfig{
				Formatting: tw.CellFormatting{
					MergeMode: tw.MergeHierarchical,
					Alignment: tw.AlignLeft,
				},
			},
		}),
	)
	table.Header([]string{"Department", "Division", "Team", "Lead"})
	table.Bulk(data)
	table.Render()
}

Output:

┌────────────┬──────────┬──────────────┬────────┐
│ DEPARTMENT │ DIVISION │    TEAM      │  LEAD  │
├────────────┼──────────┼──────────────┼────────┤
│ Engineering│ Backend  │ API Team     │ Alice  │
│            │          ├──────────────┼────────┤
│            │          │ Database Team│ Bob    │
│            │ Frontend ├──────────────┼────────┤
│            │          │ UI Team      │ Charlie│
├────────────┼──────────┼──────────────┼────────┤
│ Marketing  │ Digital  │ SEO Team     │ Dave   │
│            │          ├──────────────┼────────┤
│            │          │ Content Team │ Eve    │
└────────────┴──────────┴──────────────┴────────┘

Note: Hierarchical merging groups repeated values (e.g., "Engineering" spans multiple rows, "Backend" spans two teams), creating a tree-like structure.

7. Custom Padding with Merging

Showcase custom padding and combined horizontal/vertical merging (inspired by TestMergeWithPadding in merge_test.go).

package main

import (
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/renderer"
	"github.com/olekukonko/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"1/1/2014", "Domain name", "Successful", "Successful"},
		{"1/1/2014", "Domain name", "Pending", "Waiting"},
		{"1/1/2014", "Domain name", "Successful", "Rejected"},
		{"", "", "TOTAL", "$145.93"},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.RendererConfig{
			Settings: tw.Settings{
				Separators: tw.Separators{BetweenRows: tw.On},
			},
		})),
		tablewriter.WithConfig(tablewriter.Config{
			Row: tw.CellConfig{
				Formatting:   tw.CellFormatting{MergeMode: tw.MergeBoth},
				ColumnAligns: []tw.Align{tw.Skip, tw.Skip, tw.AlignRight, tw.AlignLeft},
			},
			Footer: tw.CellConfig{
				Padding: tw.CellPadding{
					Global:    tw.Padding{Left: "*", Right: "*"},
					PerColumn: []tw.Padding{{}, {}, {Bottom: "^"}, {Bottom: "^"}},
				},
				ColumnAligns: []tw.Align{tw.Skip, tw.Skip, tw.AlignRight, tw.AlignLeft},
			},
		}),
	)
	table.Header([]string{"Date", "Description", "Status", "Conclusion"})
	table.Bulk(data)
	table.Render()
}

Output:

┌──────────┬─────────────┬────────────┬────────────┐
│   DATE   │ DESCRIPTION │   STATUS   │ CONCLUSION │
├──────────┼─────────────┼────────────┴────────────┤
│ 1/1/2014 │ Domain name │              Successful │
│          │             ├────────────┬────────────┤
│          │             │    Pending │ Waiting    │
│          │             ├────────────┼────────────┤
│          │             │ Successful │ Rejected   │
├──────────┼─────────────┼────────────┼────────────┤
│          │             │      TOTAL │ $145.93    │
│          │             │^^^^^^^^^^^^│^^^^^^^^^^^^│
└──────────┴─────────────┴────────────┴────────────┘
8. Nested Tables

Create a table with nested sub-tables for complex layouts (inspired by TestMasterClass in extra_test.go).

package main

import (
	"bytes"
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/renderer"
	"github.com/olekukonko/tablewriter/tw"
	"os"
)

func main() {
	// Helper to create a sub-table
	createSubTable := func(s string) string {
		var buf bytes.Buffer
		table := tablewriter.NewTable(&buf,
			tablewriter.WithRenderer(renderer.NewBlueprint(tw.RendererConfig{
				Borders: tw.BorderNone,
				Symbols: tw.NewSymbols(tw.StyleASCII),
				Settings: tw.Settings{
					Separators: tw.Separators{BetweenRows: tw.On},
					Lines:      tw.Lines{ShowFooterLine: tw.On},
				},
			})),
			tablewriter.WithConfig(tablewriter.Config{
				MaxWidth: 10,
				Row: tw.CellConfig{
					Formatting: tw.CellFormatting{Alignment: tw.AlignCenter},
				},
			}),
		)
		table.Append([]string{s, s})
		table.Append([]string{s, s})
		table.Render()
		return buf.String()
	}

	// Main table
	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.RendererConfig{
			Borders: tw.BorderNone,
			Settings: tw.Settings{
				Separators: tw.Separators{BetweenColumns: tw.On},
			},
		})),
		tablewriter.WithConfig(tablewriter.Config{
			MaxWidth: 30,
			Row: tw.CellConfig{
				Formatting: tw.CellFormatting{Alignment: tw.AlignCenter},
			},
		}),
	)
	table.Append([]string{createSubTable("A"), createSubTable("B")})
	table.Append([]string{createSubTable("C"), createSubTable("D")})
	table.Render()
}

Output:

  A | A  │  B | B  
 ---+--- │ ---+--- 
  A | A  │  B | B  
 ---+--- │ ---+--- 
         │         
  C | C  │  D | D  
 ---+--- │ ---+--- 
  C | C  │  D | D  
 ---+--- │ ---+--- 
         │         
9. Structs with Database

Render a table from a slice of structs, simulating a database query (inspired by TestStructTableWithDB in struct_test.go).

package main

import (
	"fmt"
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/renderer"
	"github.com/olekukonko/tablewriter/tw"
	"os"
)

type Employee struct {
	ID         int
	Name       string
	Age        int
	Department string
	Salary     float64
}

func employeeStringer(e interface{}) []string {
	emp, ok := e.(Employee)
	if !ok {
		return []string{"Error: Invalid type"}
	}
	return []string{
		fmt.Sprintf("%d", emp.ID),
		emp.Name,
		fmt.Sprintf("%d", emp.Age),
		emp.Department,
		fmt.Sprintf("%.2f", emp.Salary),
	}
}

func main() {
	employees := []Employee{
		{ID: 1, Name: "Alice Smith", Age: 28, Department: "Engineering", Salary: 75000.50},
		{ID: 2, Name: "Bob Johnson", Age: 34, Department: "Marketing", Salary: 62000.00},
		{ID: 3, Name: "Charlie Brown", Age: 45, Department: "HR", Salary: 80000.75},
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewBlueprint(tw.RendererConfig{
			Symbols: tw.NewSymbols(tw.StyleRounded),
		})),
		tablewriter.WithStringer(employeeStringer),
		tablewriter.WithConfig(tablewriter.Config{
			Header: tw.CellConfig{
				Formatting: tw.CellFormatting{Alignment: tw.AlignCenter, AutoFormat: true},
			},
			Row: tw.CellConfig{
				Formatting: tw.CellFormatting{Alignment: tw.AlignLeft},
			},
			Footer: tw.CellConfig{
				Formatting: tw.CellFormatting{Alignment: tw.AlignRight},
			},
		}),
	)
	table.Header([]string{"ID", "Name", "Age", "Department", "Salary"})

	for _, emp := range employees {
		table.Append(emp)
	}

	totalSalary := 0.0
	for _, emp := range employees {
		totalSalary += emp.Salary
	}
	table.Footer([]string{"", "", "", "Total", fmt.Sprintf("%.2f", totalSalary)})
	table.Render()
}

Output:

╭────┬───────────────┬─────┬─────────────┬───────────╮
│ ID │     NAME      │ AGE │ DEPARTMENT  │  SALARY   │
├────┼───────────────┼─────┼─────────────┼───────────┤
│ 1  │ Alice Smith   │ 28  │ Engineering │ 75000.50  │
│ 2  │ Bob Johnson   │ 34  │ Marketing   │ 62000.00  │
│ 3  │ Charlie Brown │ 45  │ HR          │ 80000.75  │
├────┼───────────────┼─────┼─────────────┼───────────┤
│    │               │     │       Total │ 217001.25 │
╰────┴───────────────┴─────┴─────────────┴───────────╯
10. Simple Html Table
package main

import (
	"github.com/olekukonko/tablewriter"
	"github.com/olekukonko/tablewriter/renderer"
	"github.com/olekukonko/tablewriter/tw"
	"os"
)

func main() {
	data := [][]string{
		{"North", "Q1 & Q2", "Q1 & Q2", "$2200.00"},
		{"South", "Q1", "Q1", "$1000.00"},
		{"South", "Q2", "Q2", "$1200.00"},
	}

	// Configure HTML with custom CSS classes and content escaping
	htmlCfg := renderer.HTMLConfig{
		TableClass:     "sales-table",
		HeaderClass:    "table-header",
		BodyClass:      "table-body",
		FooterClass:    "table-footer",
		RowClass:       "table-row",
		HeaderRowClass: "header-row",
		FooterRowClass: "footer-row",
		EscapeContent:  true, // Escape HTML characters (e.g., "&" to "&")
	}

	table := tablewriter.NewTable(os.Stdout,
		tablewriter.WithRenderer(renderer.NewHTML(os.Stdout, false, htmlCfg)),
		tablewriter.WithConfig(tablewriter.Config{
			Header: tw.CellConfig{
				Formatting: tw.CellFormatting{
					Alignment: tw.AlignCenter,
					MergeMode: tw.MergeHorizontal, // Merge identical header cells
				},
			},
			Row: tw.CellConfig{
				Formatting: tw.CellFormatting{
					MergeMode: tw.MergeHorizontal, // Merge identical row cells
					Alignment: tw.AlignLeft,
				},
			},
			Footer: tw.CellConfig{
				Formatting: tw.CellFormatting{Alignment: tw.AlignRight},
			},
		}),
	)

	table.Header([]string{"Region", "Quarter", "Quarter", "Sales"})
	table.Bulk(data)
	table.Footer([]string{"", "", "Total", "$4400.00"})
	table.Render()
}

Output:

<table class="sales-table">
    <thead class="table-header">
        <tr class="header-row">
            <th style="text-align: center;">REGION</th>
            <th colspan="2" style="text-align: center;">QUARTER</th>
            <th style="text-align: center;">SALES</th>
        </tr>
    </thead>
    <tbody class="table-body">
        <tr class="table-row">
            <td style="text-align: left;">North</td>
            <td colspan="2" style="text-align: left;">Q1 &amp; Q2</td>
            <td style="text-align: left;">$2200.00</td>
        </tr>
        <tr class="table-row">
            <td style="text-align: left;">South</td>
            <td colspan="2" style="text-align: left;">Q1</td>
            <td style="text-align: left;">$1000.00</td>
        </tr>
        <tr class="table-row">
            <td style="text-align: left;">South</td>
            <td colspan="2" style="text-align: left;">Q2</td>
            <td style="text-align: left;">$1200.00</td>
        </tr>
    </tbody>
    <tfoot class="table-footer">
        <tr class="footer-row">
            <td style="text-align: right;"></td>
            <td style="text-align: right;"></td>
            <td style="text-align: right;">Total</td>
            <td style="text-align: right;">$4400.00</td>
        </tr>
    </tfoot>
</table>

Command-Line Tool

The csv2table tool converts CSV files to ASCII tables. See cmd/csv2table/csv2table.go for details.

Example usage:

csv2table -f test.csv -h true -a left

Contributing

Contributions are welcome! Submit issues or pull requests to the GitHub repository.

License

MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ColumnConfigBuilder added in v1.0.0

type ColumnConfigBuilder struct {
	// contains filtered or unexported fields
}

ColumnConfigBuilder configures column-specific overrides across all sections.

func (*ColumnConfigBuilder) Build added in v1.0.0

func (c *ColumnConfigBuilder) Build() *ConfigBuilder

Build returns to the parent ConfigBuilder.

func (*ColumnConfigBuilder) WithAlignment added in v1.0.0

func (c *ColumnConfigBuilder) WithAlignment(align tw.Align) *ColumnConfigBuilder

WithAlignment sets the alignment for a specific column in the header section only. (Could be expanded to affect all sections if desired)

func (*ColumnConfigBuilder) WithMaxWidth added in v1.0.0

func (c *ColumnConfigBuilder) WithMaxWidth(width int) *ColumnConfigBuilder

WithMaxWidth sets the maximum width for a specific column in all sections.

type Config added in v1.0.0

type Config struct {
	MaxWidth int           // Maximum width of the entire table (0 for unlimited)
	Header   tw.CellConfig // Configuration for the header section
	Row      tw.CellConfig // Configuration for the row section
	Footer   tw.CellConfig // Configuration for the footer section
	Debug    bool          // Enables debug logging when true
}

Config represents the overall configuration for a table.

type ConfigBuilder added in v1.0.0

type ConfigBuilder struct {
	// contains filtered or unexported fields
}

ConfigBuilder provides a fluent interface for building a Config struct. It combines direct methods for common settings with nested builders for advanced configuration.

func NewConfigBuilder added in v1.0.0

func NewConfigBuilder() *ConfigBuilder

NewConfigBuilder creates a new ConfigBuilder initialized with default settings.

func (*ConfigBuilder) Build added in v1.0.0

func (b *ConfigBuilder) Build() Config

Build returns the finalized Config struct after all modifications.

func (*ConfigBuilder) Footer added in v1.0.0

func (b *ConfigBuilder) Footer() *FooterConfigBuilder

Footer returns a builder for advanced footer configuration.

func (*ConfigBuilder) ForColumn added in v1.0.0

func (b *ConfigBuilder) ForColumn(col int) *ColumnConfigBuilder

ForColumn returns a builder for column-specific overrides across all sections.

func (*ConfigBuilder) Header added in v1.0.0

func (b *ConfigBuilder) Header() *HeaderConfigBuilder

Header returns a builder for advanced header configuration.

func (*ConfigBuilder) Row added in v1.0.0

func (b *ConfigBuilder) Row() *RowConfigBuilder

Row returns a builder for advanced row configuration.

func (*ConfigBuilder) WithDebug added in v1.0.0

func (b *ConfigBuilder) WithDebug(debug bool) *ConfigBuilder

WithDebug enables or disables debug logging for the table.

func (*ConfigBuilder) WithFooterAlignment added in v1.0.0

func (b *ConfigBuilder) WithFooterAlignment(align tw.Align) *ConfigBuilder

WithFooterAlignment sets the text alignment for all footer cells.

func (*ConfigBuilder) WithFooterAutoFormat added in v1.0.0

func (b *ConfigBuilder) WithFooterAutoFormat(autoFormat bool) *ConfigBuilder

WithFooterAutoFormat enables or disables automatic formatting for footer cells.

func (*ConfigBuilder) WithFooterAutoWrap added in v1.0.0

func (b *ConfigBuilder) WithFooterAutoWrap(autoWrap int) *ConfigBuilder

WithFooterAutoWrap sets the wrapping behavior for footer cells.

func (*ConfigBuilder) WithFooterGlobalPadding added in v1.0.0

func (b *ConfigBuilder) WithFooterGlobalPadding(padding tw.Padding) *ConfigBuilder

WithFooterGlobalPadding sets the global padding for all footer cells.

func (*ConfigBuilder) WithFooterMaxWidth added in v1.0.0

func (b *ConfigBuilder) WithFooterMaxWidth(maxWidth int) *ConfigBuilder

WithFooterMaxWidth sets the maximum content width for footer cells.

func (*ConfigBuilder) WithFooterMergeMode added in v1.0.0

func (b *ConfigBuilder) WithFooterMergeMode(mergeMode int) *ConfigBuilder

WithFooterMergeMode sets the merge behavior for footer cells.

func (*ConfigBuilder) WithHeaderAlignment added in v1.0.0

func (b *ConfigBuilder) WithHeaderAlignment(align tw.Align) *ConfigBuilder

WithHeaderAlignment sets the text alignment for all header cells.

func (*ConfigBuilder) WithHeaderAutoFormat added in v1.0.0

func (b *ConfigBuilder) WithHeaderAutoFormat(autoFormat bool) *ConfigBuilder

WithHeaderAutoFormat enables or disables automatic formatting (e.g., title case) for header cells.

func (*ConfigBuilder) WithHeaderAutoWrap added in v1.0.0

func (b *ConfigBuilder) WithHeaderAutoWrap(autoWrap int) *ConfigBuilder

WithHeaderAutoWrap sets the wrapping behavior for header cells (e.g., WrapNormal, WrapTruncate).

func (*ConfigBuilder) WithHeaderGlobalPadding added in v1.0.0

func (b *ConfigBuilder) WithHeaderGlobalPadding(padding tw.Padding) *ConfigBuilder

WithHeaderGlobalPadding sets the global padding for all header cells.

func (*ConfigBuilder) WithHeaderMaxWidth added in v1.0.0

func (b *ConfigBuilder) WithHeaderMaxWidth(maxWidth int) *ConfigBuilder

WithHeaderMaxWidth sets the maximum content width for header cells.

func (*ConfigBuilder) WithHeaderMergeMode added in v1.0.0

func (b *ConfigBuilder) WithHeaderMergeMode(mergeMode int) *ConfigBuilder

WithHeaderMergeMode sets the merge behavior for header cells (e.g., MergeHorizontal, MergeVertical).

func (*ConfigBuilder) WithMaxWidth added in v1.0.0

func (b *ConfigBuilder) WithMaxWidth(width int) *ConfigBuilder

WithMaxWidth sets the maximum width for the entire table (0 means unlimited).

func (*ConfigBuilder) WithRowAlignment added in v1.0.0

func (b *ConfigBuilder) WithRowAlignment(align tw.Align) *ConfigBuilder

WithRowAlignment sets the text alignment for all row cells.

func (*ConfigBuilder) WithRowAutoFormat added in v1.0.0

func (b *ConfigBuilder) WithRowAutoFormat(autoFormat bool) *ConfigBuilder

WithRowAutoFormat enables or disables automatic formatting for row cells.

func (*ConfigBuilder) WithRowAutoWrap added in v1.0.0

func (b *ConfigBuilder) WithRowAutoWrap(autoWrap int) *ConfigBuilder

WithRowAutoWrap sets the wrapping behavior for row cells.

func (*ConfigBuilder) WithRowGlobalPadding added in v1.0.0

func (b *ConfigBuilder) WithRowGlobalPadding(padding tw.Padding) *ConfigBuilder

WithRowGlobalPadding sets the global padding for all row cells.

func (*ConfigBuilder) WithRowMaxWidth added in v1.0.0

func (b *ConfigBuilder) WithRowMaxWidth(maxWidth int) *ConfigBuilder

WithRowMaxWidth sets the maximum content width for row cells.

func (*ConfigBuilder) WithRowMergeMode added in v1.0.0

func (b *ConfigBuilder) WithRowMergeMode(mergeMode int) *ConfigBuilder

WithRowMergeMode sets the merge behavior for row cells.

type FooterConfigBuilder added in v1.0.0

type FooterConfigBuilder struct {
	// contains filtered or unexported fields
}

FooterConfigBuilder provides advanced configuration for the footer section. (Similar structure to HeaderConfigBuilder, omitted for brevity)

func (*FooterConfigBuilder) Build added in v1.0.0

func (f *FooterConfigBuilder) Build() *ConfigBuilder

func (*FooterConfigBuilder) Formatting added in v1.0.0

func (*FooterConfigBuilder) Padding added in v1.0.0

type FooterFormattingBuilder added in v1.0.0

type FooterFormattingBuilder struct {
	// contains filtered or unexported fields
}

FooterFormattingBuilder configures formatting options for the footer.

func (*FooterFormattingBuilder) Build added in v1.0.0

func (*FooterFormattingBuilder) WithAlignment added in v1.0.0

func (ff *FooterFormattingBuilder) WithAlignment(align tw.Align) *FooterFormattingBuilder

func (*FooterFormattingBuilder) WithAutoFormat added in v1.0.0

func (ff *FooterFormattingBuilder) WithAutoFormat(autoFormat bool) *FooterFormattingBuilder

func (*FooterFormattingBuilder) WithAutoWrap added in v1.0.0

func (ff *FooterFormattingBuilder) WithAutoWrap(autoWrap int) *FooterFormattingBuilder

func (*FooterFormattingBuilder) WithMaxWidth added in v1.0.0

func (ff *FooterFormattingBuilder) WithMaxWidth(maxWidth int) *FooterFormattingBuilder

func (*FooterFormattingBuilder) WithMergeMode added in v1.0.0

func (ff *FooterFormattingBuilder) WithMergeMode(mergeMode int) *FooterFormattingBuilder

type FooterPaddingBuilder added in v1.0.0

type FooterPaddingBuilder struct {
	// contains filtered or unexported fields
}

FooterPaddingBuilder configures padding options for the footer.

func (*FooterPaddingBuilder) AddColumnPadding added in v1.0.0

func (fp *FooterPaddingBuilder) AddColumnPadding(padding tw.Padding) *FooterPaddingBuilder

func (*FooterPaddingBuilder) Build added in v1.0.0

func (*FooterPaddingBuilder) WithGlobal added in v1.0.0

func (fp *FooterPaddingBuilder) WithGlobal(padding tw.Padding) *FooterPaddingBuilder

func (*FooterPaddingBuilder) WithPerColumn added in v1.0.0

func (fp *FooterPaddingBuilder) WithPerColumn(padding []tw.Padding) *FooterPaddingBuilder

type HeaderConfigBuilder added in v1.0.0

type HeaderConfigBuilder struct {
	// contains filtered or unexported fields
}

HeaderConfigBuilder provides advanced configuration for the header section.

func (*HeaderConfigBuilder) Build added in v1.0.0

func (h *HeaderConfigBuilder) Build() *ConfigBuilder

Build returns to the parent ConfigBuilder.

func (*HeaderConfigBuilder) Formatting added in v1.0.0

Formatting returns a builder for header formatting settings.

func (*HeaderConfigBuilder) Padding added in v1.0.0

Padding returns a builder for header padding settings.

type HeaderFormattingBuilder added in v1.0.0

type HeaderFormattingBuilder struct {
	// contains filtered or unexported fields
}

HeaderFormattingBuilder configures formatting options for the header.

func (*HeaderFormattingBuilder) Build added in v1.0.0

func (*HeaderFormattingBuilder) WithAlignment added in v1.0.0

func (hf *HeaderFormattingBuilder) WithAlignment(align tw.Align) *HeaderFormattingBuilder

func (*HeaderFormattingBuilder) WithAutoFormat added in v1.0.0

func (hf *HeaderFormattingBuilder) WithAutoFormat(autoFormat bool) *HeaderFormattingBuilder

func (*HeaderFormattingBuilder) WithAutoWrap added in v1.0.0

func (hf *HeaderFormattingBuilder) WithAutoWrap(autoWrap int) *HeaderFormattingBuilder

func (*HeaderFormattingBuilder) WithMaxWidth added in v1.0.0

func (hf *HeaderFormattingBuilder) WithMaxWidth(maxWidth int) *HeaderFormattingBuilder

func (*HeaderFormattingBuilder) WithMergeMode added in v1.0.0

func (hf *HeaderFormattingBuilder) WithMergeMode(mergeMode int) *HeaderFormattingBuilder

type HeaderPaddingBuilder added in v1.0.0

type HeaderPaddingBuilder struct {
	// contains filtered or unexported fields
}

HeaderPaddingBuilder configures padding options for the header.

func (*HeaderPaddingBuilder) AddColumnPadding added in v1.0.0

func (hp *HeaderPaddingBuilder) AddColumnPadding(padding tw.Padding) *HeaderPaddingBuilder

func (*HeaderPaddingBuilder) Build added in v1.0.0

func (*HeaderPaddingBuilder) WithGlobal added in v1.0.0

func (hp *HeaderPaddingBuilder) WithGlobal(padding tw.Padding) *HeaderPaddingBuilder

func (*HeaderPaddingBuilder) WithPerColumn added in v1.0.0

func (hp *HeaderPaddingBuilder) WithPerColumn(padding []tw.Padding) *HeaderPaddingBuilder

type Option added in v1.0.0

type Option func(*Table)

Option defines a function to configure a Table instance.

func WithConfig added in v1.0.0

func WithConfig(cfg Config) Option

WithConfig applies a custom configuration to the table.

func WithDebug added in v1.0.0

func WithDebug(debug bool) Option

WithDebug enables or disables debug logging.

func WithFooter added in v1.0.0

func WithFooter(footers []string) Option

WithFooter sets the table footers.

func WithFooterConfig added in v1.0.0

func WithFooterConfig(config tw.CellConfig) Option

WithFooterConfig applies a full footer configuration.

func WithFooterMergeMode added in v1.0.0

func WithFooterMergeMode(mergeMode int) Option

WithFooterMergeMode sets the footer merge mode directly.

func WithHeader added in v1.0.0

func WithHeader(headers []string) Option

WithHeader sets the table headers.

func WithHeaderAlignment added in v1.0.0

func WithHeaderAlignment(align tw.Align) Option

WithHeaderAlignment sets the header alignment directly.

func WithHeaderConfig added in v1.0.0

func WithHeaderConfig(config tw.CellConfig) Option

WithHeaderConfig applies a full header configuration.

func WithRenderer added in v1.0.0

func WithRenderer(f tw.Renderer) Option

WithRenderer sets a custom renderer for the table.

func WithRowConfig added in v1.0.0

func WithRowConfig(config tw.CellConfig) Option

WithRowConfig applies a full row configuration.

func WithRowMaxWidth added in v1.0.0

func WithRowMaxWidth(maxWidth int) Option

WithRowMaxWidth sets the row max width directly.

func WithStringer added in v1.0.0

func WithStringer[T any](s func(T) []string) Option

WithStringer sets a custom stringer function for row conversion.

type RowConfigBuilder added in v1.0.0

type RowConfigBuilder struct {
	// contains filtered or unexported fields
}

RowConfigBuilder provides advanced configuration for the row section. (Similar structure to HeaderConfigBuilder, omitted for brevity but follows the same pattern)

func (*RowConfigBuilder) Build added in v1.0.0

func (r *RowConfigBuilder) Build() *ConfigBuilder

func (*RowConfigBuilder) Formatting added in v1.0.0

func (r *RowConfigBuilder) Formatting() *RowFormattingBuilder

func (*RowConfigBuilder) Padding added in v1.0.0

func (r *RowConfigBuilder) Padding() *RowPaddingBuilder

type RowFormattingBuilder added in v1.0.0

type RowFormattingBuilder struct {
	// contains filtered or unexported fields
}

RowFormattingBuilder configures formatting options for rows.

func (*RowFormattingBuilder) Build added in v1.0.0

func (*RowFormattingBuilder) WithAlignment added in v1.0.0

func (rf *RowFormattingBuilder) WithAlignment(align tw.Align) *RowFormattingBuilder

func (*RowFormattingBuilder) WithAutoFormat added in v1.0.0

func (rf *RowFormattingBuilder) WithAutoFormat(autoFormat bool) *RowFormattingBuilder

func (*RowFormattingBuilder) WithAutoWrap added in v1.0.0

func (rf *RowFormattingBuilder) WithAutoWrap(autoWrap int) *RowFormattingBuilder

func (*RowFormattingBuilder) WithMaxWidth added in v1.0.0

func (rf *RowFormattingBuilder) WithMaxWidth(maxWidth int) *RowFormattingBuilder

func (*RowFormattingBuilder) WithMergeMode added in v1.0.0

func (rf *RowFormattingBuilder) WithMergeMode(mergeMode int) *RowFormattingBuilder

type RowPaddingBuilder added in v1.0.0

type RowPaddingBuilder struct {
	// contains filtered or unexported fields
}

RowPaddingBuilder configures padding options for rows.

func (*RowPaddingBuilder) AddColumnPadding added in v1.0.0

func (rp *RowPaddingBuilder) AddColumnPadding(padding tw.Padding) *RowPaddingBuilder

func (*RowPaddingBuilder) Build added in v1.0.0

func (rp *RowPaddingBuilder) Build() *RowConfigBuilder

func (*RowPaddingBuilder) WithGlobal added in v1.0.0

func (rp *RowPaddingBuilder) WithGlobal(padding tw.Padding) *RowPaddingBuilder

func (*RowPaddingBuilder) WithPerColumn added in v1.0.0

func (rp *RowPaddingBuilder) WithPerColumn(padding []tw.Padding) *RowPaddingBuilder

type Table

type Table struct {
	// contains filtered or unexported fields
}

Table represents a table instance with content and rendering capabilities.

func NewCSV

func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error)

NewCSV Start A new table by importing from a CSV file Takes io.Writer and csv File name

func NewCSVReader

func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool) (*Table, error)

NewCSVReader Start a New Table Writer with csv.Reader This enables customisation such as reader.Comma = ';' See http://golang.org/src/pkg/encoding/csv/reader.go?s=3213:3671#L94

func NewTable added in v1.0.0

func NewTable(w io.Writer, opts ...Option) *Table

NewTable creates a new table instance with the specified writer and options. Options can customize the table's configuration.

func NewWriter

func NewWriter(w io.Writer) *Table

NewWriter creates a new table with default settings for backward compatibility.

func (*Table) Append

func (t *Table) Append(rows ...interface{}) error

Append adds one or more rows to the table. Rows can be of any type if a stringer is provided.

func (*Table) Bulk added in v1.0.0

func (t *Table) Bulk(rows interface{}) error

Bulk adds multiple rows from a slice to the table (legacy method). Expects a slice of rows compatible with the stringer or []string.

func (*Table) Configure added in v1.0.0

func (t *Table) Configure(fn func(*Config)) *Table

func (*Table) Debug added in v1.0.0

func (t *Table) Debug() []string

Debug returns the accumulated debug trace, including renderer logs.

func (*Table) Footer added in v1.0.0

func (t *Table) Footer(footers []string)

Footer configures the table's footer content, padding to match column count. Multi-line footers are supported.

func (*Table) Header added in v1.0.0

func (t *Table) Header(headers []string)

Header configures the table's header content. Multi-line headers are supported via prepareContent.

func (*Table) Render

func (t *Table) Render() error

Render triggers the table rendering process to the writer. Returns an error if rendering fails.

func (*Table) Renderer added in v1.0.0

func (t *Table) Renderer() tw.Renderer

Renderer returns the current renderer instance used by the table.

type TableStream added in v1.0.0

type TableStream struct {
	// contains filtered or unexported fields
}

TableStream provides an interface for incrementally rendering table rows using a compatible Streamer. It requires pre-defined column widths or other configuration needed by the specific streaming renderer.

func NewStreamTable added in v1.0.0

func NewStreamTable(w io.Writer, renderer tw.Streamer) (*TableStream, error)

NewStreamTable creates a new table configured for streaming output. It takes the output writer and a pre-configured Streamer.

func (*TableStream) Debug added in v1.0.0

func (st *TableStream) Debug() []string

Debug returns the debug trace from the underlying renderer.

func (*TableStream) End added in v1.0.0

func (st *TableStream) End() error

End finalizes the table stream, rendering the bottom border/closing tags. This should be called once after all headers, rows, and footers have been streamed.

func (*TableStream) Footer added in v1.0.0

func (st *TableStream) Footer(footer []string) error

Footer renders a single footer row. Can be called multiple times.

func (*TableStream) Header added in v1.0.0

func (st *TableStream) Header(header []string) error

Header renders a single header row. Can be called multiple times if needed, although most streaming renderers will assume a single primary header row.

func (*TableStream) Row added in v1.0.0

func (st *TableStream) Row(row []string) error

Row renders a single data row. Call this repeatedly for each row in the stream.

func (*TableStream) Start added in v1.0.0

func (st *TableStream) Start() error

Start initializes the table stream and renders the top border/opening tags. This should be called once before streaming any headers or rows.

Directories

Path Synopsis
cmd
csv2table command
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL