golang终端彩色表格生成插件库table的使用

Golang终端彩色表格生成插件库table的使用

简介

Table是一个用于在命令行中打印彩色表格数据的Golang库,它使用ANSI颜色转义代码来美化输出。支持通过结构体字段自动生成表格,也支持手动创建表格对象。

使用方法

手动创建表格

tab := table.Table{
    Headers: []string{"something", "another"},
    Rows: [][]string{
        {"1", "2"},
        {"3", "4"},
        {"3", "a longer piece of text that should stretch"},
        {"but this one is longer", "shorter now"},
    },
}
err := tab.WriteTable(w, nil) // w是任何io.Writer

simple example

使用结构体切片

data := []struct {
    Name     string `table:"THE NAME"`
    Location string `table:"THE LOCATION"`
}{
    {"name", "l"},
    {"namgfcxe", "asfdad"},
    {"namr3e", "l134151dsa"},
    {"namear", "lasd2135"},
}

err := table.MarshalTo(w, data, nil) // 写入到任何io.Writer
buf, err := table.Marshal(data, nil) // 也支持返回字节

reflection

表格配置

nil参数是表格的配置,可以手动设置,如果留空则使用默认配置。

type Config struct {
    ShowIndex       bool     // 在第一列显示索引/行号
    Color           bool     // 在输出中使用颜色代码
    AlternateColors bool     // 写入时交替使用颜色
    TitleColorCode  string   // 标题行的ANSI代码
    AltColorCodes   []string // 交替使用的ANSI代码
}

安装

使用go get命令安装:

$ go get github.com/mattn/go-colorable

许可证

MIT

作者

Tom Lazar


更多关于golang终端彩色表格生成插件库table的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang终端彩色表格生成插件库table的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Golang 终端彩色表格生成 - table 库使用指南

在 Golang 中生成终端彩色表格可以使用 github.com/jedib0t/go-pretty/v6/table 这个功能强大的库。下面我将详细介绍它的使用方法。

安装

go get github.com/jedib0t/go-pretty/v6/table

基本使用

package main

import (
	"os"

	"github.com/jedib0t/go-pretty/v6/table"
)

func main() {
	// 创建表格
	t := table.NewWriter()
	t.SetOutputMirror(os.Stdout)
	
	// 添加表头
	t.AppendHeader(table.Row{"ID", "Name", "Age", "Salary"})
	
	// 添加数据行
	t.AppendRows([]table.Row{
		{1, "John Doe", 30, "$100,000"},
		{2, "Jane Smith", 28, "$95,000"},
		{3, "Bob Johnson", 35, "$120,000"},
	})
	
	// 添加页脚
	t.AppendFooter(table.Row{"", "", "Total", "$315,000"})
	
	// 设置表格样式
	t.SetStyle(table.StyleColoredBright)
	
	// 渲染表格
	t.Render()
}

自定义样式

// 创建自定义样式
customStyle := table.Style{
	Name: "MyStyle",
	Box: table.BoxStyle{
		BottomLeft:       "╚",
		BottomRight:      "╝",
		BottomSeparator:  "╩",
		Left:            "╠",
		LeftSeparator:   "╬",
		MiddleHorizontal: "═",
		MiddleSeparator:  "╬",
		MiddleVertical:   "║",
		PaddingLeft:     " ",
		PaddingRight:    " ",
		Right:           "╣",
		RightSeparator:  "╬",
		TopLeft:         "╔",
		TopRight:        "╗",
		TopSeparator:    "╦",
	},
	Color: table.ColorOptions{
		Header:       text.Colors{text.BgHiCyan, text.FgBlack},
		Row:          text.Colors{text.FgHiWhite},
		RowAlternate: text.Colors{text.FgHiGreen},
	},
	Format: table.FormatOptions{
		Header: text.FormatUpper,
	},
	Options: table.Options{
		DrawBorder:      true,
		SeparateColumns: true,
		SeparateHeader:  true,
		SeparateRows:    false,
	},
}

t.SetStyle(customStyle)

高级功能

1. 列配置

t.SetColumnConfigs([]table.ColumnConfig{
	{
		Name:     "Salary",
		Align:    text.AlignRight,
		VAlign:   text.VAlignMiddle,
		Colors:   text.Colors{text.BgHiRed, text.FgHiWhite},
		WidthMax: 20,
	},
	{
		Name:     "Age",
		Align:    text.AlignCenter,
		Colors:   text.Colors{text.FgHiYellow},
		WidthMin: 10,
	},
})

2. 排序和过滤

// 按年龄降序排序
t.SortBy([]table.SortBy{
	{Name: "Age", Mode: table.Dsc},
})

// 过滤年龄大于30的记录
t.RowPainter = func(row table.Row) text.Colors {
	age := row[2].(int)
	if age > 30 {
		return text.Colors{text.BgHiBlue, text.FgBlack}
	}
	return nil
}

3. 自动合并单元格

t.AppendRow(table.Row{"", "Same Dept", 25, "$80,000"})
t.AppendRow(table.Row{"", "Same Dept", 27, "$85,000"})

t.SetAutoMerge(true)

4. 分页显示

t.SetPageSize(2) // 每页显示2行
t.Render()       // 渲染第一页
t.Render()       // 渲染第二页

内置样式

库提供了多种内置样式,可以直接使用:

t.SetStyle(table.StyleColoredBright)      // 彩色明亮风格
t.SetStyle(table.StyleColoredDark)        // 彩色暗色风格
t.SetStyle(table.StyleColoredBlackOnBlueWhite) // 蓝底白字
t.SetStyle(table.StyleDouble)             // 双线边框
t.SetStyle(table.StyleLight)              // 轻量风格
t.SetStyle(table.StyleRounded)            // 圆角边框

输出到字符串

如果不希望直接输出到终端,可以获取表格字符串:

output := t.RenderString()
fmt.Println(output)

完整示例

package main

import (
	"os"

	"github.com/jedib0t/go-pretty/v6/table"
	"github.com/jedib0t/go-pretty/v6/text"
)

func main() {
	t := table.NewWriter()
	t.SetOutputMirror(os.Stdout)
	t.AppendHeader(table.Row{"ID", "Name", "Age", "Salary", "Department"})
	
	t.AppendRows([]table.Row{
		{1, "John Doe", 30, "$100,000", "Engineering"},
		{2, "Jane Smith", 28, "$95,000", "Marketing"},
		{3, "Bob Johnson", 35, "$120,000", "Engineering"},
		{4, "Alice Brown", 32, "$110,000", "HR"},
	})
	
	t.AppendFooter(table.Row{"", "", "", "$425,000", ""})
	
	// 自定义样式
	t.SetStyle(table.Style{
		Name: "MyStyle",
		Box: table.BoxStyle{
			BottomLeft:       "╚",
			BottomRight:      "╝",
			BottomSeparator:  "╩",
			Left:            "╠",
			LeftSeparator:   "╬",
			MiddleHorizontal: "═",
			MiddleSeparator:  "╬",
			MiddleVertical:   "║",
			PaddingLeft:     " ",
			PaddingRight:    " ",
			Right:           "╣",
			RightSeparator:  "╬",
			TopLeft:         "╔",
			TopRight:        "╗",
			TopSeparator:    "╦",
		},
		Color: table.ColorOptions{
			Header:       text.Colors{text.BgHiMagenta, text.FgBlack},
			Footer:       text.Colors{text.BgHiRed, text.FgBlack},
			Row:          text.Colors{text.FgHiWhite},
			RowAlternate: text.Colors{text.FgHiGreen},
		},
		Options: table.Options{
			DrawBorder:      true,
			SeparateColumns: true,
			SeparateHeader:  true,
			SeparateRows:    false,
		},
	})
	
	// 列配置
	t.SetColumnConfigs([]table.ColumnConfig{
		{
			Name:     "Salary",
			Align:    text.AlignRight,
			Colors:   text.Colors{text.BgHiBlue, text.FgHiWhite},
			WidthMax: 20,
		},
		{
			Name:     "Department",
			Align:    text.AlignCenter,
			Colors:   text.Colors{text.FgHiYellow},
			WidthMin: 15,
		},
	})
	
	// 自动合并相同部门
	t.SetAutoMerge(true)
	
	t.Render()
}

这个库功能非常强大,支持各种自定义选项,可以生成美观的终端彩色表格。你可以根据需要调整样式、颜色和布局。

回到顶部