tablewriter

package module
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2021 License: MIT Imports: 12 Imported by: 7

README

ASCII Table Writer

ci Total views Godoc

Generate ASCII table on the fly ... Installation is simple as

go get github.com/olekukonko/tablewriter
Features
  • Automatic Padding
  • Support Multiple Lines
  • Supports Alignment
  • Support Custom Separators
  • Automatic Alignment of numbers & percentage
  • Write directly to http , file etc via io.Writer
  • Read directly from CSV file
  • Optional row line via SetRowLine
  • Normalise table header
  • Make CSV Headers optional
  • Enable or disable table border
  • Set custom footer support
  • Optional identical cells merging
  • Set custom caption
  • Optional reflowing of paragraphs in multi-line cells.
Example 1 - Basic
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
Output 1
+------+-----------------------+--------+
| NAME |         SIGN          | RATING |
+------+-----------------------+--------+
|  A   |       The Good        |    500 |
|  B   | The Very very Bad Man |    288 |
|  C   |       The Ugly        |    120 |
|  D   |      The Gopher       |    800 |
+------+-----------------------+--------+
data := [][]string{
    []string{"1/1/2014", "Domain name", "2233", "$10.98"},
    []string{"1/1/2014", "January Hosting", "2233", "$54.95"},
    []string{"1/4/2014", "February Hosting", "2233", "$51.00"},
    []string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer
table.SetBorder(false)                                // Set Border to false
table.AppendBulk(data)                                // Add Bulk Data
table.Render()
Output 2

    DATE   |       DESCRIPTION        |  CV2  | AMOUNT
-----------+--------------------------+-------+----------
  1/1/2014 | Domain name              |  2233 | $10.98
  1/1/2014 | January Hosting          |  2233 | $54.95
  1/4/2014 | February Hosting         |  2233 | $51.00
  1/4/2014 | February Extra Bandwidth |  2233 | $30.00
-----------+--------------------------+-------+----------
                                        TOTAL | $146 93
                                      --------+----------

Example 3 - CSV
table, _ := tablewriter.NewCSV(os.Stdout, "testdata/test_info.csv", true)
table.SetAlignment(tablewriter.ALIGN_LEFT)   // Set Alignment
table.Render()
Output 3
+----------+--------------+------+-----+---------+----------------+
|  FIELD   |     TYPE     | NULL | KEY | DEFAULT |     EXTRA      |
+----------+--------------+------+-----+---------+----------------+
| user_id  | smallint(5)  | NO   | PRI | NULL    | auto_increment |
| username | varchar(10)  | NO   |     | NULL    |                |
| password | varchar(100) | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
Example 4 - Custom Separator
table, _ := tablewriter.NewCSV(os.Stdout, "testdata/test.csv", true)
table.SetRowLine(true)         // Enable row line

// Change table lines
table.SetCenterSeparator("*")
table.SetColumnSeparator("╪")
table.SetRowSeparator("-")

table.SetAlignment(tablewriter.ALIGN_LEFT)
table.Render()
Output 4
*------------*-----------*---------*
╪ FIRST NAME ╪ LAST NAME ╪   SSN   ╪
*------------*-----------*---------*
╪ John       ╪ Barry     ╪ 123456  ╪
*------------*-----------*---------*
╪ Kathy      ╪ Smith     ╪ 687987  ╪
*------------*-----------*---------*
╪ Bob        ╪ McCornick ╪ 3979870 ╪
*------------*-----------*---------*
Example 5 - Markdown Format
data := [][]string{
	[]string{"1/1/2014", "Domain name", "2233", "$10.98"},
	[]string{"1/1/2014", "January Hosting", "2233", "$54.95"},
	[]string{"1/4/2014", "February Hosting", "2233", "$51.00"},
	[]string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetCenterSeparator("|")
table.AppendBulk(data) // Add Bulk Data
table.Render()
Output 5
|   DATE   |       DESCRIPTION        | CV2  | AMOUNT |
|----------|--------------------------|------|--------|
| 1/1/2014 | Domain name              | 2233 | $10.98 |
| 1/1/2014 | January Hosting          | 2233 | $54.95 |
| 1/4/2014 | February Hosting         | 2233 | $51.00 |
| 1/4/2014 | February Extra Bandwidth | 2233 | $30.00 |
Example 6 - Identical cells merging
data := [][]string{
  []string{"1/1/2014", "Domain name", "1234", "$10.98"},
  []string{"1/1/2014", "January Hosting", "2345", "$54.95"},
  []string{"1/4/2014", "February Hosting", "3456", "$51.00"},
  []string{"1/4/2014", "February Extra Bandwidth", "4567", "$30.00"},
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
table.SetFooter([]string{"", "", "Total", "$146.93"})
table.SetAutoMergeCells(true)
table.SetRowLine(true)
table.AppendBulk(data)
table.Render()
Output 6
+----------+--------------------------+-------+---------+
|   DATE   |       DESCRIPTION        |  CV2  | AMOUNT  |
+----------+--------------------------+-------+---------+
| 1/1/2014 | Domain name              |  1234 | $10.98  |
+          +--------------------------+-------+---------+
|          | January Hosting          |  2345 | $54.95  |
+----------+--------------------------+-------+---------+
| 1/4/2014 | February Hosting         |  3456 | $51.00  |
+          +--------------------------+-------+---------+
|          | February Extra Bandwidth |  4567 | $30.00  |
+----------+--------------------------+-------+---------+
|                                       TOTAL | $146 93 |
+----------+--------------------------+-------+---------+
Example 7 - Identical cells merging (specify the column index to merge)
data := [][]string{
  []string{"1/1/2014", "Domain name", "1234", "$10.98"},
  []string{"1/1/2014", "January Hosting", "1234", "$10.98"},
  []string{"1/4/2014", "February Hosting", "3456", "$51.00"},
  []string{"1/4/2014", "February Extra Bandwidth", "4567", "$30.00"},
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
table.SetFooter([]string{"", "", "Total", "$146.93"})
table.SetAutoMergeCellsByColumnIndex([]int{2, 3})
table.SetRowLine(true)
table.AppendBulk(data)
table.Render()
Output 7
+----------+--------------------------+-------+---------+
|   DATE   |       DESCRIPTION        |  CV2  | AMOUNT  |
+----------+--------------------------+-------+---------+
| 1/1/2014 | Domain name              |  1234 | $10.98  |
+----------+--------------------------+       +         +
| 1/1/2014 | January Hosting          |       |         |
+----------+--------------------------+-------+---------+
| 1/4/2014 | February Hosting         |  3456 | $51.00  |
+----------+--------------------------+-------+---------+
| 1/4/2014 | February Extra Bandwidth |  4567 | $30.00  |
+----------+--------------------------+-------+---------+
|                                       TOTAL | $146.93 |
+----------+--------------------------+-------+---------+
Table with color
data := [][]string{
	[]string{"1/1/2014", "Domain name", "2233", "$10.98"},
	[]string{"1/1/2014", "January Hosting", "2233", "$54.95"},
	[]string{"1/4/2014", "February Hosting", "2233", "$51.00"},
	[]string{"1/4/2014", "February Extra Bandwidth", "2233", "$30.00"},
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Date", "Description", "CV2", "Amount"})
table.SetFooter([]string{"", "", "Total", "$146.93"}) // Add Footer
table.SetBorder(false)                                // Set Border to false

table.SetHeaderColor(tablewriter.Colors{tablewriter.Bold, tablewriter.BgGreenColor},
	tablewriter.Colors{tablewriter.FgHiRedColor, tablewriter.Bold, tablewriter.BgBlackColor},
	tablewriter.Colors{tablewriter.BgRedColor, tablewriter.FgWhiteColor},
	tablewriter.Colors{tablewriter.BgCyanColor, tablewriter.FgWhiteColor})

table.SetColumnColor(tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiBlackColor},
	tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor},
	tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiBlackColor},
	tablewriter.Colors{tablewriter.Bold, tablewriter.FgBlackColor})

table.SetFooterColor(tablewriter.Colors{}, tablewriter.Colors{},
	tablewriter.Colors{tablewriter.Bold},
	tablewriter.Colors{tablewriter.FgHiRedColor})

table.AppendBulk(data)
table.Render()
Table with color Output

Table with Color

Example - 8 Table Cells with Color

Individual Cell Colors from func Rich take precedence over Column Colors

data := [][]string{
	[]string{"Test1Merge", "HelloCol2 - 1", "HelloCol3 - 1", "HelloCol4 - 1"},
	[]string{"Test1Merge", "HelloCol2 - 2", "HelloCol3 - 2", "HelloCol4 - 2"},
	[]string{"Test1Merge", "HelloCol2 - 3", "HelloCol3 - 3", "HelloCol4 - 3"},
	[]string{"Test2Merge", "HelloCol2 - 4", "HelloCol3 - 4", "HelloCol4 - 4"},
	[]string{"Test2Merge", "HelloCol2 - 5", "HelloCol3 - 5", "HelloCol4 - 5"},
	[]string{"Test2Merge", "HelloCol2 - 6", "HelloCol3 - 6", "HelloCol4 - 6"},
	[]string{"Test2Merge", "HelloCol2 - 7", "HelloCol3 - 7", "HelloCol4 - 7"},
	[]string{"Test3Merge", "HelloCol2 - 8", "HelloCol3 - 8", "HelloCol4 - 8"},
	[]string{"Test3Merge", "HelloCol2 - 9", "HelloCol3 - 9", "HelloCol4 - 9"},
	[]string{"Test3Merge", "HelloCol2 - 10", "HelloCol3 -10", "HelloCol4 - 10"},
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Col1", "Col2", "Col3", "Col4"})
table.SetFooter([]string{"", "", "Footer3", "Footer4"})
table.SetBorder(false)

table.SetHeaderColor(tablewriter.Colors{tablewriter.Bold, tablewriter.BgGreenColor},
	tablewriter.Colors{tablewriter.FgHiRedColor, tablewriter.Bold, tablewriter.BgBlackColor},
	tablewriter.Colors{tablewriter.BgRedColor, tablewriter.FgWhiteColor},
	tablewriter.Colors{tablewriter.BgCyanColor, tablewriter.FgWhiteColor})

table.SetColumnColor(tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiBlackColor},
	tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiRedColor},
	tablewriter.Colors{tablewriter.Bold, tablewriter.FgHiBlackColor},
	tablewriter.Colors{tablewriter.Bold, tablewriter.FgBlackColor})

table.SetFooterColor(tablewriter.Colors{}, tablewriter.Colors{},
	tablewriter.Colors{tablewriter.Bold},
	tablewriter.Colors{tablewriter.FgHiRedColor})

colorData1 := []string{"TestCOLOR1Merge", "HelloCol2 - COLOR1", "HelloCol3 - COLOR1", "HelloCol4 - COLOR1"}
colorData2 := []string{"TestCOLOR2Merge", "HelloCol2 - COLOR2", "HelloCol3 - COLOR2", "HelloCol4 - COLOR2"}

for i, row := range data {
	if i == 4 {
		table.Rich(colorData1, []tablewriter.Colors{tablewriter.Colors{}, tablewriter.Colors{tablewriter.Normal, tablewriter.FgCyanColor}, tablewriter.Colors{tablewriter.Bold, tablewriter.FgWhiteColor}, tablewriter.Colors{}})
		table.Rich(colorData2, []tablewriter.Colors{tablewriter.Colors{tablewriter.Normal, tablewriter.FgMagentaColor}, tablewriter.Colors{}, tablewriter.Colors{tablewriter.Bold, tablewriter.BgRedColor}, tablewriter.Colors{tablewriter.FgHiGreenColor, tablewriter.Italic, tablewriter.BgHiCyanColor}})
	}
	table.Append(row)
}

table.SetAutoMergeCells(true)
table.Render()

Table cells with color Output

Table cells with Color

Example 9 - Set table caption
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"})
table.SetCaption(true, "Movie ratings.")

for _, v := range data {
    table.Append(v)
}
table.Render() // Send output

Note: Caption text will wrap with total width of rendered table.

Output 9
+------+-----------------------+--------+
| NAME |         SIGN          | RATING |
+------+-----------------------+--------+
|  A   |       The Good        |    500 |
|  B   | The Very very Bad Man |    288 |
|  C   |       The Ugly        |    120 |
|  D   |      The Gopher       |    800 |
+------+-----------------------+--------+
Movie ratings.
Example 10 - Set NoWhiteSpace and TablePadding option
data := [][]string{
    {"node1.example.com", "Ready", "compute", "1.11"},
    {"node2.example.com", "Ready", "compute", "1.11"},
    {"node3.example.com", "Ready", "compute", "1.11"},
    {"node4.example.com", "NotReady", "compute", "1.11"},
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Status", "Role", "Version"})
table.SetAutoWrapText(false)
table.SetAutoFormatHeaders(true)
table.SetHeaderAlignment(ALIGN_LEFT)
table.SetAlignment(ALIGN_LEFT)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.SetHeaderLine(false)
table.SetBorder(false)
table.SetTablePadding("\t") // pad with tabs
table.SetNoWhiteSpace(true)
table.AppendBulk(data) // Add Bulk Data
table.Render()
Output 10
NAME             	STATUS  	ROLE   	VERSION 
node1.example.com	Ready   	compute	1.11   	
node2.example.com	Ready   	compute	1.11   	
node3.example.com	Ready   	compute	1.11   	
node4.example.com	NotReady	compute	1.11   	
Render table into a string

Instead of rendering the table to io.Stdout you can also render it into a string. Go 1.10 introduced the strings.Builder type which implements the io.Writer interface and can therefore be used for this task. Example:

package main

import (
    "strings"
    "fmt"

    "github.com/olekukonko/tablewriter"
)

func main() {
    tableString := &strings.Builder{}
    table := tablewriter.NewWriter(tableString)

    /*
     * Code to fill the table
     */

    table.Render()

    fmt.Println(tableString.String())
}
TODO
  • Import Directly from CSV - done
  • Support for SetFooter - done
  • Support for SetBorder - done
  • Support table with uneven rows - done
  • Support custom alignment
  • General Improvement & Optimisation
  • NewHTML Parse table from HTML

Documentation

Overview

Create & Generate text based table

Example (Autowrap)
var multiline = `A multiline
string with some lines being really long.`

const (
	testRow = iota
	testHeader
	testFooter
	testFooter2
)
for mode := testRow; mode <= testFooter2; mode++ {
	for _, autoFmt := range []bool{false, true} {
		if mode == testRow && autoFmt {
			// Nothing special to test, skip
			continue
		}
		for _, autoWrap := range []bool{false, true} {
			for _, reflow := range []bool{false, true} {
				if !autoWrap && reflow {
					// Invalid configuration, skip
					continue
				}
				fmt.Println("mode", mode, "autoFmt", autoFmt, "autoWrap", autoWrap, "reflow", reflow)
				t := NewWriter(os.Stdout)
				t.SetAutoFormatHeaders(autoFmt)
				t.SetAutoWrapText(autoWrap)
				t.SetReflowDuringAutoWrap(reflow)
				if mode == testHeader {
					t.SetHeader([]string{"woo", multiline})
				} else {
					t.SetHeader([]string{"woo", "waa"})
				}
				if mode == testRow {
					t.Append([]string{"woo", multiline})
				} else {
					t.Append([]string{"woo", "waa"})
				}
				if mode == testFooter {
					t.SetFooter([]string{"woo", multiline})
				} else if mode == testFooter2 {
					t.SetFooter([]string{"", multiline})
				} else {
					t.SetFooter([]string{"woo", "waa"})
				}
				t.Render()
			}
		}
	}
	fmt.Println()
}
Output:

mode 0 autoFmt false autoWrap false reflow false
+-----+-------------------------------------------+
| woo |                    waa                    |
+-----+-------------------------------------------+
| woo | A multiline                               |
|     | string with some lines being really long. |
+-----+-------------------------------------------+
| woo |                    waa                    |
+-----+-------------------------------------------+
mode 0 autoFmt false autoWrap true reflow false
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
| woo | A multiline                    |
|     |                                |
|     | string with some lines being   |
|     | really long.                   |
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
mode 0 autoFmt false autoWrap true reflow true
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
| woo | A multiline string with some   |
|     | lines being really long.       |
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+

mode 1 autoFmt false autoWrap false reflow false
+-----+-------------------------------------------+
| woo |                A multiline                |
|     | string with some lines being really long. |
+-----+-------------------------------------------+
| woo | waa                                       |
+-----+-------------------------------------------+
| woo |                    waa                    |
+-----+-------------------------------------------+
mode 1 autoFmt false autoWrap true reflow false
+-----+--------------------------------+
| woo |          A multiline           |
|     |                                |
|     |  string with some lines being  |
|     |          really long.          |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
mode 1 autoFmt false autoWrap true reflow true
+-----+--------------------------------+
| woo |  A multiline string with some  |
|     |    lines being really long.    |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
mode 1 autoFmt true autoWrap false reflow false
+-----+-------------------------------------------+
| WOO |                A MULTILINE                |
|     | STRING WITH SOME LINES BEING REALLY LONG  |
+-----+-------------------------------------------+
| woo | waa                                       |
+-----+-------------------------------------------+
| WOO |                    WAA                    |
+-----+-------------------------------------------+
mode 1 autoFmt true autoWrap true reflow false
+-----+--------------------------------+
| WOO |          A MULTILINE           |
|     |                                |
|     |  STRING WITH SOME LINES BEING  |
|     |          REALLY LONG           |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| WOO |              WAA               |
+-----+--------------------------------+
mode 1 autoFmt true autoWrap true reflow true
+-----+--------------------------------+
| WOO |  A MULTILINE STRING WITH SOME  |
|     |    LINES BEING REALLY LONG     |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| WOO |              WAA               |
+-----+--------------------------------+

mode 2 autoFmt false autoWrap false reflow false
+-----+-------------------------------------------+
| woo |                    waa                    |
+-----+-------------------------------------------+
| woo | waa                                       |
+-----+-------------------------------------------+
| woo |                A multiline                |
|     | string with some lines being really long. |
+-----+-------------------------------------------+
mode 2 autoFmt false autoWrap true reflow false
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| woo |          A multiline           |
|     |                                |
|     |  string with some lines being  |
|     |          really long.          |
+-----+--------------------------------+
mode 2 autoFmt false autoWrap true reflow true
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| woo |  A multiline string with some  |
|     |    lines being really long.    |
+-----+--------------------------------+
mode 2 autoFmt true autoWrap false reflow false
+-----+-------------------------------------------+
| WOO |                    WAA                    |
+-----+-------------------------------------------+
| woo | waa                                       |
+-----+-------------------------------------------+
| WOO |                A MULTILINE                |
|     | STRING WITH SOME LINES BEING REALLY LONG  |
+-----+-------------------------------------------+
mode 2 autoFmt true autoWrap true reflow false
+-----+--------------------------------+
| WOO |              WAA               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| WOO |          A MULTILINE           |
|     |                                |
|     |  STRING WITH SOME LINES BEING  |
|     |          REALLY LONG           |
+-----+--------------------------------+
mode 2 autoFmt true autoWrap true reflow true
+-----+--------------------------------+
| WOO |              WAA               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
| WOO |  A MULTILINE STRING WITH SOME  |
|     |    LINES BEING REALLY LONG     |
+-----+--------------------------------+

mode 3 autoFmt false autoWrap false reflow false
+-----+-------------------------------------------+
| woo |                    waa                    |
+-----+-------------------------------------------+
| woo | waa                                       |
+-----+-------------------------------------------+
|                      A multiline                |
|       string with some lines being really long. |
+-----+-------------------------------------------+
mode 3 autoFmt false autoWrap true reflow false
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
|                A multiline           |
|                                      |
|        string with some lines being  |
|                really long.          |
+-----+--------------------------------+
mode 3 autoFmt false autoWrap true reflow true
+-----+--------------------------------+
| woo |              waa               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
|        A multiline string with some  |
|          lines being really long.    |
+-----+--------------------------------+
mode 3 autoFmt true autoWrap false reflow false
+-----+-------------------------------------------+
| WOO |                    WAA                    |
+-----+-------------------------------------------+
| woo | waa                                       |
+-----+-------------------------------------------+
|                      A MULTILINE                |
|       STRING WITH SOME LINES BEING REALLY LONG  |
+-----+-------------------------------------------+
mode 3 autoFmt true autoWrap true reflow false
+-----+--------------------------------+
| WOO |              WAA               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
|                A MULTILINE           |
|                                      |
|        STRING WITH SOME LINES BEING  |
|                REALLY LONG           |
+-----+--------------------------------+
mode 3 autoFmt true autoWrap true reflow true
+-----+--------------------------------+
| WOO |              WAA               |
+-----+--------------------------------+
| woo | waa                            |
+-----+--------------------------------+
|        A MULTILINE STRING WITH SOME  |
|          LINES BEING REALLY LONG     |
+-----+--------------------------------+

Index

Examples

Constants

View Source
const (
	CENTER  = "+"
	ROW     = "-"
	COLUMN  = "|"
	SPACE   = " "
	NEWLINE = "\n"
)
View Source
const (
	ALIGN_DEFAULT = iota
	ALIGN_CENTER
	ALIGN_RIGHT
	ALIGN_LEFT
)
View Source
const (
	BgBlackColor int = iota + 40
	BgRedColor
	BgGreenColor
	BgYellowColor
	BgBlueColor
	BgMagentaColor
	BgCyanColor
	BgWhiteColor
)
View Source
const (
	FgBlackColor int = iota + 30
	FgRedColor
	FgGreenColor
	FgYellowColor
	FgBlueColor
	FgMagentaColor
	FgCyanColor
	FgWhiteColor
)
View Source
const (
	BgHiBlackColor int = iota + 100
	BgHiRedColor
	BgHiGreenColor
	BgHiYellowColor
	BgHiBlueColor
	BgHiMagentaColor
	BgHiCyanColor
	BgHiWhiteColor
)
View Source
const (
	FgHiBlackColor int = iota + 90
	FgHiRedColor
	FgHiGreenColor
	FgHiYellowColor
	FgHiBlueColor
	FgHiMagentaColor
	FgHiCyanColor
	FgHiWhiteColor
)
View Source
const (
	Normal          = 0
	Bold            = 1
	UnderlineSingle = 4
	Italic
)
View Source
const ESC = "\033"
View Source
const (
	MAX_ROW_WIDTH = 30
)
View Source
const SEP = ";"

Variables

This section is empty.

Functions

func Color

func Color(colors ...int) []int

func ConditionString

func ConditionString(cond bool, valid, inValid string) string

Simple Condition for string Returns value based on condition

func DisplayWidth

func DisplayWidth(str string) int

func Pad

func Pad(s, pad string, width int) string

Pad String Attempts to place string in the center

func PadLeft

func PadLeft(s, pad string, width int) string

Pad String Left position This would place string at the right side of the screen

func PadRight

func PadRight(s, pad string, width int) string

Pad String Right position This would place string at the left side of the screen

func Title

func Title(name string) string

Format Table Header Replace _ , . and spaces

func WrapString

func WrapString(s string, lim int) ([]string, int)

Wrap wraps s into a paragraph of lines of length lim, with minimal raggedness.

func WrapWords

func WrapWords(words []string, spc, lim, pen int) [][]string

WrapWords is the low-level line-breaking algorithm, useful if you need more control over the details of the text wrapping process. For most uses, WrapString will be sufficient and more convenient.

WrapWords splits a list of words into lines with minimal "raggedness", treating each rune as one unit, accounting for spc units between adjacent words on each line, and attempting to limit lines to lim units. Raggedness is the total error over all lines, where error is the square of the difference of the length of the line and lim. Too-long lines (which only happen when a single word is longer than lim units) have pen penalty units added to the error.

Types

type Border

type Border struct {
	Left   bool
	Right  bool
	Top    bool
	Bottom bool
}

type Colors

type Colors []int

type Table

type Table struct {
	// contains filtered or unexported fields
}
Example
data := [][]string{
	{"Learn East has computers with adapted keyboards with enlarged print etc", "  Some Data  ", " Another Data"},
	{"Instead of lining up the letters all ", "the way across, he splits the keyboard in two", "Like most ergonomic keyboards", "See Data"},
}

table := NewWriter(os.Stdout)
table.SetHeader([]string{"Name", "Sign", "Rating"})
table.SetCenterSeparator("*")
table.SetRowSeparator("=")

for _, v := range data {
	table.Append(v)
}
table.Render()
Output:

*================================*================================*===============================*==========*
|              NAME              |              SIGN              |            RATING             |          |
*================================*================================*===============================*==========*
| Learn East has computers       |   Some Data                    |  Another Data                 |
| with adapted keyboards with    |                                |                               |
| enlarged print etc             |                                |                               |
| Instead of lining up the       | the way across, he splits the  | Like most ergonomic keyboards | See Data |
| letters all                    | keyboard in two                |                               |          |
*================================*================================*===============================*==========*

func NewCSV

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

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

Example
table, _ := NewCSV(os.Stdout, "testdata/test.csv", true)
table.SetCenterSeparator("*")
table.SetRowSeparator("=")

table.Render()
Output:

*============*===========*=========*
| FIRST NAME | LAST NAME |   SSN   |
*============*===========*=========*
| John       | Barry     |  123456 |
| Kathy      | Smith     |  687987 |
| Bob        | McCornick | 3979870 |
*============*===========*=========*

func NewCSVReader

func NewCSVReader(writer io.Writer, csvReader *csv.Reader, hasHeader bool) (*Table, error)
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 NewWriter

func NewWriter(writer io.Writer) *Table

Start New Table Take io.Writer Directly

func (*Table) AddSeparator added in v0.0.6

func (t *Table) AddSeparator()

func (*Table) Append

func (t *Table) Append(row []string)

Append row to table

func (*Table) AppendBulk

func (t *Table) AppendBulk(rows [][]string)

Allow Support for Bulk Append Eliminates repeated for loops

func (*Table) ClearFooter

func (t *Table) ClearFooter()

Clear footer

func (*Table) ClearRows

func (t *Table) ClearRows()

Clear rows

func (*Table) NumLines

func (t *Table) NumLines() int

NumLines to get the number of lines

func (*Table) Render

func (t *Table) Render()

Render table output

func (*Table) Rich added in v0.0.5

func (t *Table) Rich(row []string, colors []Colors)

Append row to table with color attributes

func (*Table) SetAlignment

func (t *Table) SetAlignment(align int)

Set Table Alignment

func (*Table) SetAutoFormatHeaders

func (t *Table) SetAutoFormatHeaders(auto bool)

Turn header autoformatting on/off. Default is on (true).

func (*Table) SetAutoMergeCells

func (t *Table) SetAutoMergeCells(auto bool)

Set Auto Merge Cells This would enable / disable the merge of cells with identical values

func (*Table) SetAutoMergeCellsByColumnIndex added in v0.0.8

func (t *Table) SetAutoMergeCellsByColumnIndex(cols []int)

Set Auto Merge Cells By Column Index This would enable / disable the merge of cells with identical values for specific columns If cols is empty, it is the same as `SetAutoMergeCells(true)`.

func (*Table) SetAutoWrapText

func (t *Table) SetAutoWrapText(auto bool)

Turn automatic multiline text adjustment on/off. Default is on (true).

func (*Table) SetBorder

func (t *Table) SetBorder(border bool)

Set Table Border This would enable / disable line around the table

func (*Table) SetBorders

func (t *Table) SetBorders(border Border)

func (*Table) SetCaption

func (t *Table) SetCaption(caption bool, captionText ...string)

Set table Caption

func (*Table) SetCenterSeparator

func (t *Table) SetCenterSeparator(sep string)

Set the center Separator

func (*Table) SetColMinWidth

func (t *Table) SetColMinWidth(column int, width int)

Set the minimal width for a column

func (*Table) SetColWidth

func (t *Table) SetColWidth(width int)

Set the Default column width

func (*Table) SetColumnAlignment

func (t *Table) SetColumnAlignment(keys []int)

func (*Table) SetColumnColor

func (t *Table) SetColumnColor(colors ...Colors)

Adding column colors (ANSI codes)

func (*Table) SetColumnSeparator

func (t *Table) SetColumnSeparator(sep string)

Set the Column Separator

func (*Table) SetFooter

func (t *Table) SetFooter(keys []string)

Set table Footer

func (*Table) SetFooterAlignment

func (t *Table) SetFooterAlignment(fAlign int)

Set Footer Alignment

func (*Table) SetFooterColor

func (t *Table) SetFooterColor(colors ...Colors)

Adding column colors (ANSI codes)

func (*Table) SetHeader

func (t *Table) SetHeader(keys []string)

Set table header

func (*Table) SetHeaderAlignment

func (t *Table) SetHeaderAlignment(hAlign int)

Set Header Alignment

func (*Table) SetHeaderColor

func (t *Table) SetHeaderColor(colors ...Colors)

Adding header colors (ANSI codes)

func (*Table) SetHeaderLine

func (t *Table) SetHeaderLine(line bool)

Set Header Line This would enable / disable a line after the header

func (*Table) SetNewLine

func (t *Table) SetNewLine(nl string)

Set New Line

func (*Table) SetNoWhiteSpace added in v0.0.5

func (t *Table) SetNoWhiteSpace(allow bool)

Set No White Space

func (*Table) SetReflowDuringAutoWrap

func (t *Table) SetReflowDuringAutoWrap(auto bool)

Turn automatic reflowing of multiline text when rewrapping. Default is on (true).

func (*Table) SetRowLine

func (t *Table) SetRowLine(line bool)

Set Row Line This would enable / disable a line on each row of the table

func (*Table) SetRowSeparator

func (t *Table) SetRowSeparator(sep string)

Set the Row Separator

func (*Table) SetStructs added in v0.0.10

func (t *Table) SetStructs(v interface{}) error

SetStructs sets header and rows from slice of struct. If something that is not a slice is passed, error will be returned. The tag specified by "tablewriter" for the struct becomes the header. If not specified or empty, the field name will be used. The field of the first element of the slice is used as the header. If the element implements fmt.Stringer, the result will be used. And the slice contains nil, it will be skipped without rendering.

func (*Table) SetTablePadding added in v0.0.5

func (t *Table) SetTablePadding(padding string)

Set Table Padding

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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