prettytable

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2025 License: BSD-3-Clause Imports: 7 Imported by: 0

README

prettytable (Go)

A Go port of the Python PrettyTable package. Display tabular data in ASCII, Unicode, Markdown, CSV, HTML, JSON, LaTeX, and MediaWiki formats.

Go Reference

Features

  • Create tables with custom field (column) names
  • Add rows one by one or all at once
  • Add columns one by one
  • Delete rows and columns
  • Sort and filter rows
  • Control column alignment (left, center, right)
  • Section dividers (add_divider)
  • Advanced style options (borders, padding, custom chars)
  • Output formats: ASCII, Unicode, Markdown, CSV, HTML, JSON, LaTeX, MediaWiki
  • Import from CSV or database rows

Installation

go get github.com/deny-7/prettytable

Usage

Basic Example
package main

import (
	"fmt"
	"github.com/deny-7/prettytable"
)

func main() {
	t := prettytable.NewTableWithFields([]string{"City name", "Area", "Population", "Annual Rainfall"})
	t.AddRows([][]any{
		{"Adelaide", 1295, 1158259, 600.5},
		{"Brisbane", 5905, 1857594, 1146.4},
		{"Darwin", 112, 120900, 1714.7},
	})
	fmt.Println(t)
}
Adding Data
Row by row
t := prettytable.NewTable()
t.SetFieldNames([]string{"City name", "Area", "Population", "Annual Rainfall"})
t.AddRow([]any{"Adelaide", 1295, 1158259, 600.5})
t.AddRow([]any{"Brisbane", 5905, 1857594, 1146.4})
All rows at once
t := prettytable.NewTableWithFields([]string{"City name", "Area", "Population", "Annual Rainfall"})
t.AddRows([][]any{
	{"Adelaide", 1295, 1158259, 600.5},
	{"Brisbane", 5905, 1857594, 1146.4},
	{"Darwin", 112, 120900, 1714.7},
})
Column by column
t := prettytable.NewTable()
t.AddColumn("City name", []any{"Adelaide", "Brisbane", "Darwin"})
t.AddColumn("Area", []any{1295, 5905, 112})
t.AddColumn("Population", []any{1158259, 1857594, 120900})
t.AddColumn("Annual Rainfall", []any{600.5, 1146.4, 1714.7})
Importing from CSV
f, _ := os.Open("myfile.csv")
table, _ := prettytable.FromCSV(f, ',')
Importing from database rows
rows, _ := db.Query("SELECT name, area, population, rainfall FROM cities")
table, _ := prettytable.FromDBRows(rows)
Output Formats
fmt.Println(table.RenderASCII())      // ASCII
fmt.Println(table.RenderUnicode())    // Unicode box-drawing
fmt.Println(table.RenderMarkdown())   // Markdown
fmt.Println(table.RenderCSV())        // CSV
fmt.Println(table.RenderJSON())       // JSON
fmt.Println(table.RenderHTML())       // HTML
fmt.Println(table.RenderLaTeX())      // LaTeX
fmt.Println(table.RenderMediaWiki())  // MediaWiki

Or use:

fmt.Println(table.GetFormattedString("markdown"))
Advanced Features
Section Dividers
t.AddRow([]any{"Adelaide", 1295, 1158259, 600.5})
t.AddDivider()
t.AddRow([]any{"Brisbane", 5905, 1857594, 1146.4})
Sorting and Filtering
t.SetSortBy("Population", true) // Sort by Population descending
t.SetRowFilter(func(row []any) bool { return row[2].(int) > 1000000 }) // Only large cities
Alignment
t.SetAlign("City name", prettytable.AlignLeft)
t.SetAlign("Population", prettytable.AlignRight)
t.SetAlignAll(prettytable.AlignCenter)
Custom Style
style := prettytable.TableStyle{
	Border:         false,
	PaddingWidth:   1,
	VerticalChar:   ".",
	HorizontalChar: "_",
	JunctionChar:   "*",
}
t.SetStyle(style)

Example Output

ASCII:

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 | 1158259    | 600.5           |
| Brisbane  | 5905 | 1857594    | 1146.4          |
| Darwin    | 112  | 120900     | 1714.7          |
+-----------+------+------------+-----------------+

Markdown:

| City name | Area | Population | Annual Rainfall |
| --- | --- | --- | --- |
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |

Unicode:

┌───────────┬──────┬────────────┬─────────────────┐
│ City name │ Area │ Population │ Annual Rainfall │
├───────────┼──────┼────────────┼─────────────────┤
│ Adelaide  │ 1295 │ 1158259    │ 600.5           │
│ Brisbane  │ 5905 │ 1857594    │ 1146.4          │
│ Darwin    │ 112  │ 120900     │ 1714.7          │
└───────────┴──────┴────────────┴─────────────────┘

API Reference

See GoDoc: https://pkg.go.dev/github.com/deny-7/prettytable

License

Ported to Go by Denys Bondar, 2025 Based on original work by Luke Maurits and contributors Licensed under the BSD 3-Clause License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Alignment

type Alignment int

Alignment type for column alignment Left, Center, Right

const (
	AlignLeft Alignment = iota
	AlignCenter
	AlignRight
)

type Table

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

Table represents a table with field names and rows Only ASCII rendering is implemented for now

func FromCSV

func FromCSV(r io.Reader, delim rune) (*Table, error)

FromCSV reads CSV data from an io.Reader and returns a new Table.

func FromDBRows

func FromDBRows(rows *sql.Rows) (*Table, error)

FromDBRows creates a Table from a *sql.Rows result set.

func NewTable

func NewTable() *Table

NewTable creates a new empty table

func NewTableWithFields

func NewTableWithFields(fields []string) *Table

NewTableWithFields creates a new table with field names

func (*Table) AddColumn

func (t *Table) AddColumn(field string, column []any) error

AddColumn adds a column to the table with the given field name and column data.

func (*Table) AddRow

func (t *Table) AddRow(row []any) error

AddRow adds a row to the table

func (*Table) Clear

func (t *Table) Clear()

Clear deletes all rows and field names.

func (*Table) ClearRows

func (t *Table) ClearRows()

ClearRows deletes all rows but keeps field names.

func (*Table) DelColumn

func (t *Table) DelColumn(field string) error

DelColumn deletes a column by field name.

func (*Table) DelRow

func (t *Table) DelRow(index int) error

DelRow deletes a row at the given index.

func (*Table) FieldNames

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

FieldNames returns the field names

func (*Table) GetFormattedString

func (t *Table) GetFormattedString(format string) string

GetFormattedString returns the table as a string in the specified format. Supported formats: "text", "ascii", "csv", "json", "html", "latex", "mediawiki", "markdown"

func (*Table) RenderASCII

func (t *Table) RenderASCII() string

RenderASCII renders the table as an ASCII string

func (*Table) RenderCSV

func (t *Table) RenderCSV() string

RenderCSV renders the table as CSV

func (*Table) RenderHTML

func (t *Table) RenderHTML() string

RenderHTML renders the table as an HTML table

func (*Table) RenderJSON

func (t *Table) RenderJSON() string

RenderJSON renders the table as JSON array of objects

func (*Table) RenderLaTeX

func (t *Table) RenderLaTeX() string

RenderLaTeX renders the table as LaTeX tabular

func (*Table) RenderMarkdown

func (t *Table) RenderMarkdown() string

RenderMarkdown renders the table as GitHub-flavored Markdown

func (*Table) RenderMediaWiki

func (t *Table) RenderMediaWiki() string

RenderMediaWiki renders the table as MediaWiki markup

func (*Table) RenderText

func (t *Table) RenderText() string

RenderText renders the table as plain text (same as ASCII)

func (*Table) RenderUnicode

func (t *Table) RenderUnicode() string

RenderUnicode renders the table using Unicode box-drawing characters

func (*Table) SetAlign

func (t *Table) SetAlign(field string, align Alignment)

SetAlign sets the alignment for a column by field name.

func (*Table) SetAlignAll

func (t *Table) SetAlignAll(align Alignment)

SetAlignAll sets the alignment for all columns.

func (*Table) SetFieldNames

func (t *Table) SetFieldNames(fields []string)

SetFieldNames sets the field (column) names

func (*Table) SetRowFilter

func (t *Table) SetRowFilter(filter func([]any) bool)

SetRowFilter sets a filter function for rows.

func (*Table) SetSortBy

func (t *Table) SetSortBy(field string, reverse bool)

SetSortBy sets the field to sort by and order.

func (*Table) SetStyle

func (t *Table) SetStyle(style TableStyle)

SetStyle sets the table style options

func (*Table) String

func (t *Table) String() string

String renders the table as ASCII (implements fmt.Stringer)

type TableStyle

type TableStyle struct {
	Border                  bool
	PreserveInternalBorder  bool
	Header                  bool
	HRule                   string // "FRAME", "HEADER", "ALL", "NONE"
	VRule                   string // "FRAME", "ALL", "NONE"
	IntFormat               string // e.g. ",d" or "03d"
	FloatFormat             string // e.g. ".2f"
	CustomFormat            map[string]func(field string, value any) string
	PaddingWidth            int
	LeftPaddingWidth        int
	RightPaddingWidth       int
	VerticalChar            string
	HorizontalChar          string
	HorizontalAlignChar     string
	JunctionChar            string
	TopJunctionChar         string
	BottomJunctionChar      string
	RightJunctionChar       string
	LeftJunctionChar        string
	TopRightJunctionChar    string
	TopLeftJunctionChar     string
	BottomRightJunctionChar string
	BottomLeftJunctionChar  string
	MinTableWidth           int
	MaxTableWidth           int
	MaxWidth                int
	MinWidth                int
	UseHeaderWidth          *bool
	BreakOnHyphens          *bool
}

TableStyle holds options for customizing table appearance All fields are optional; zero values mean default behavior

Jump to

Keyboard shortcuts

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