百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

tablewriter

> 编程语言
开源

golang 中的 ASCII 表

4.8K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

golang 中的 ASCII 表

TableWriter for Go

tablewriter is a Go library for generating rich text-based tables with support for multiple output formats, including ASCII, Unicode, Markdown, HTML, and colorized terminals. Perfect for CLI tools, logs, and web applications.

Key Features

  • Multi-format rendering: ASCII, Unicode, Markdown, HTML, ANSI-colored
  • Advanced styling: Cell merging, alignment, padding, borders
  • Flexible input: CSV, structs, slices, or streaming data
  • High performance: Minimal allocations, buffer reuse
  • Modern features: Generics support, hierarchical merging, real-time streaming

Installation

Legacy Version (v0.0.5)

For use with legacy applications:

go get github.com/olekukonko/[email protected]

Latest Version

The latest stable version

go get github.com/olekukonko/[email protected]

Warning: Version v1.0.0 contains missing functionality and should not be used.

Version Guidance

  • Legacy: Use v0.0.5 (stable)
  • New Features: Use @latest (includes generics, super fast streaming APIs)
  • Legacy Docs: See README_LEGACY.md

Why TableWriter?

  • CLI Ready: Instant compatibility with terminal outputs
  • Database Friendly: Native support for sql.Null* types
  • Secure: Auto-escaping for HTML/Markdown
  • Extensible: Custom renderers and formatters

Quick Example

package main

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

func main() {
	data := [][]string{
		{"Package", "Version", "Status"},
		{"tablewriter", "v0.0.5", "legacy"},
		{"tablewriter", "v1.1.5", "latest"},
	}

	table := tablewriter.NewWriter(os.Stdout)
	table.Header(data[0])
	table.Bulk(data[1:])
	table.Render()
}

Output:

┌─────────────┬─────────┬────────┐
│   PACKAGE   │ VERSION │ STATUS │
├─────────────┼─────────┼────────┤
│ tablewriter │ v0.0.5  │ legacy │
│ tablewriter │ v1.1.5  │ latest │
└─────────────┴─────────┴────────┘

Detailed 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).

Here's how the API primitives map to the generated ASCII table:

…

The core components include:

  • Renderer - Implements the core interface for converting table data into output formats. Available renderers include Blueprint (ASCII), HTML, Markdown, Colorized (ASCII with color), Ocean (streaming ASCII), and SVG.

  • Config - The root configuration struct that controls all table behavior and appearance

    • Behavior - Controls high-level rendering behaviors including auto-hiding empty columns, trimming row whitespace, header/footer visibility, and compact mode for optimized merged cell calculations
    • CellConfig - The comprehensive configuration template used for table sections (header, row, footer). Combines formatting, padding, alignment, filtering, callbacks, and width constraints with global and per-column control
    • StreamConfig - Configuration for streaming mode including enable/disable state and strict column validation
  • Rendition - Defines how a renderer formats tables and contains the complete visual styling configuration

    • Borders - Control the outer frame visibility (top, bottom, left, right edges) of the table
    • Lines - Control horizontal boundary lines (above/below headers, above footers) that separate different table sections
    • Separators - Control the visibility of separators between rows and between columns within the table content
    • Symbols - Define the characters used for drawing table borders, corners, and junctions

These components can be configured with various tablewriter.With*() functional options when creating a new table.

Examples

Basic Examples

1. Simple Tables

Create a basic table with headers and rows.

default
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("Name", "Age", "City")
	table.Bulk(data)
	table.Render()
}

Output:

┌───────┬────────┬──────────┐
│ NAME  │  AGE   │   CITY   │
├───────┼────────┼──────────┤
│ Alice │ 25 yrs │ New York │
│ Bob   │ 30 yrs │ Boston   │
└───────┴────────┴──────────┘
with customization
…
~~~~~~❀~~~~~~~~❀~~~~~~~~~
| NAME  |  AGE   |   CITY   |
~~~~~~❀~~~~~~~~❀~~~~~~~~~
| Alice | 25 yrs | New York |
| Bob   | 30 yrs | Boston   |
~~~~~~❀~~~~~~~~❀~~~~~~~~~

See symbols example for more

2. Markdown Table

Generate a Markdown table for documentation.

…

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.Alignment.Global = 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).

…

Output (colors visible in ANSI-compatible terminals):

24-bit (RGB / true color) tints

Besides the named color.Fg*/color.Bg* attributes, tints accept 24-bit colors. renderer.RGB and renderer.BgRGB take red, green and blue channels (0-255, out-of-range values are clamped), while renderer.Hex/renderer.BgHex parse a #RRGGBB or #RGB string. All of them return a renderer.Colors, so they slot in wherever named attributes do and can be combined with append:

orange, _ := renderer.Hex("#ff8800")

colorCfg := renderer.ColorizedConfig{
	// Bold orange headers on a dark-grey background.
	Header: renderer.Tint{
		FG: append(orange, color.Bold),
		BG: renderer.BgRGB(30, 30, 30),
	},
	// Teal rows.
	Column: renderer.Tint{FG: renderer.RGB(0, 200, 180)},
}

Terminals without true-color support may approximate or ignore these colors.

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).

…

Output (appears incrementally):

┌────────┬───────────────┬──────────┐
│   ID   │  DESCRIPTION  │  STATUS  │
├────────┼───────────────┼──────────┤
│ 1      │ This          │ OK       │
│        │ description   │          │
│        │ is too long   │          │
│ 2      │ Short desc    │ DONE     │
│ 3      │ Another long  │ ERROR    │
│        │ description   │          │
│        │ here          │          │
├────────┼───────────────┼──────────┤
│        │         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).

…

Output:

…

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).

…

Output:

…

8. Nested Tables

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

…

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).

…

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

…

Output:

…

11. SVG Support

…
…

12 Simple Application

…
…

Changes

  • AutoFormat changes See #261

What is new

  • Counting changes See #294

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.

GitHub Issues· 0 开放

在 GitHub 查看全部

暂无开放 Issues,或尚未同步最近议题。

核心特点

  • •Multi-format rendering: ASCII, Unicode, Markdown, HTML, ANSI-colored
  • •Advanced styling: Cell merging, alignment, padding, borders
  • •Flexible input: CSV, structs, slices, or streaming data
  • •High performance: Minimal allocations, buffer reuse
  • •Modern features: Generics support, hierarchical merging, real-time streaming
  • •CLI Ready: Instant compatibility with terminal outputs
  • •Database Friendly: Native support for sql.Null* types
  • •Secure: Auto-escaping for HTML/Markdown
  • •Extensible: Custom renderers and formatters
  • •Config - The root configuration struct that controls all table behavior and appearance

> 标签

Go

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言