Rust终端表格生成库uutils_term_grid的使用:高效格式化与对齐文本数据

Rust终端表格生成库uutils_term_grid的使用:高效格式化与对齐文本数据

uutils_term_grid是一个用于在固定宽度字体中排列文本数据的Rust库,它使用算法来最小化所需的空间。

安装

在Cargo.toml的dependencies部分添加:

[dependencies]
uutils_term_grid = "0.7"

最低支持的Rust版本是1.70。

创建表格

要向表格添加数据,首先使用字符串列表和一组选项创建一个新的Grid值。

GridOptions值中必须指定三个选项来决定表格如何格式化:

  1. filling:如何填充列之间的空白:

    • Filling::Spaces:列之间的空格数
    • Filling::Text:列之间的文本分隔符
    • Filling::Tabs:特殊选项,允许设置列之间的空格数并设置\t字符的大小
  2. direction:指定单元格是沿行还是列排列:

    • Direction::LeftToRight:从左上角开始向右移动,到达最后一列后转到新行的开头
    • Direction::TopToBottom:从左上角开始向下移动,到达最后一行后转到新列的顶部
  3. width:填充表格的宽度。通常这应该是终端的宽度。

示例代码

以下是创建表格的完整示例:

use term_grid::{Grid, GridOptions, Direction, Filling};

// 创建要放入表格的文本Vec
let cells = vec![
    "one", "two", "three", "four", "five", "six",
    "seven", "eight", "nine", "ten", "eleven", "twelve"
];

// 然后使用这些单元格创建一个`Grid`
// 表格需要几个选项:
//  - filling确定用作列之间分隔符的字符串
//  - direction指定布局应该是按行还是按列
//  - width是表格可能具有的最大宽度
let grid = Grid::new(
    cells,
    GridOptions {
        filling: Filling::Spaces(1),
        direction: Direction::LeftToRight,
        width: 24,
    }
);

// `Grid`实现了`Display`,可以直接打印
println!("{grid}");

这将产生以下表格结果:

one  two three  four
five six seven  eight
nine ten eleven twelve

完整示例demo

下面是一个更完整的示例,展示不同配置选项的使用:

use term_grid::{Grid, GridOptions, Direction, Filling};

fn main() {
    // 示例1:基本表格
    let cells1 = vec![
        "姓名", "年龄", "职业",
        "张三", "28", "工程师",
        "李四", "35", "设计师",
        "王五", "42", "经理"
    ];
    
    let grid1 = Grid::new(
        cells1,
        GridOptions {
            filling: Filling::Spaces(2),
            direction: Direction::LeftToRight,
            width: 30,
        }
    );
    
    println!("基本表格示例:");
    println!("{}", grid1);
    
    // 示例2:使用文本分隔符
    let cells2 = vec![
        "ID", "产品", "价格",
        "001", "笔记本电脑", "$999",
        "002", "手机", "$699",
        "003", "平板", "$499"
    ];
    
    let grid2 = Grid::new(
        cells2,
        GridOptions {
            filling: Filling::Text(" | ".to_string()),
            direction: Direction::LeftToRight,
            width: 40,
        }
    );
    
    println!("\n使用文本分隔符示例:");
    println!("{}", grid2);
    
    // 示例3:垂直排列方向
    let cells3 = vec![
        "一月", "二月", "三月", "四月",
        "五月", "六月", "七月", "八月",
        "九月", "十月", "十一月", "十二月"
    ];
    
    let grid3 = Grid::new(
        cells3,
        GridOptions {
            filling: Filling::Spaces(3),
            direction: Direction::TopToBottom,
            width: 50,
        }
    );
    
    println!("\n垂直排列方向示例:");
    println!("{}", grid3);
}

表格单元格的宽度

该库使用ansi-width crate计算字符串在终端中显示的宽度。这考虑了字符的宽度并忽略ANSI代码。

目前宽度计算不可配置。如果您有这种计算错误的用例,请提出问题。


1 回复

Rust终端表格生成库uutils_term_grid使用指南

uutils_term_grid是一个Rust库,用于在终端中生成格式整齐的表格数据。它特别适合需要将数据结构以表格形式展示的命令行工具。

主要特性

  • 自动计算列宽
  • 支持文本对齐(左、右、居中)
  • 可配置的单元格填充和分隔线
  • 处理包含多行文本的单元格
  • 支持Unicode字符

基本使用方法

首先在Cargo.toml中添加依赖:

[dependencies]
uutils_term_grid = "0.3"

简单示例

use uutils_term_grid::{Grid, GridOptions, Direction, Filling, Cell};

fn main() {
    let mut grid = Grid::new(GridOptions {
        direction: Direction::LeftToRight,
        filling: Filling::Spaces(1),
    });

    // 添加表头
    grid.add(Cell::from("Name"));
    grid.add(Cell::from("Age"));
    grid.add(Cell::from("Occupation"));

    // 添加数据行
    grid.add(Cell::from("Alice"));
    grid.add(Cell::from("28"));
    grid.add(Cell::from("Engineer"));

    grid.add(Cell::from("Bob"));
    grid.add(Cell::from("35"));
    grid.add(Cell::from("Teacher"));

    println!("{}", grid.fit_into_console(80).unwrap());
}

对齐控制

use uutils_term_grid::{Grid, GridOptions, Direction, Filling, Cell, Alignment};

let mut grid = Grid::new(GridOptions {
    direction: Direction::LeftToRight,
    filling: Filling::Spaces(2),
});

grid.add(Cell::from("Name").with_alignment(Alignment::Left));
grid.add(Cell::from("Score").with_alignment(Alignment::Right));
grid.add(Cell::from("Date").with_alignment(Alignment::Center));

grid.add(Cell::from("Alice"));
grid.add(Cell::from("95.5"));
grid.add(Cell::from("2023-01-15"));

grid.add(Cell::from("Bob"));
grid.add(Cell::from("87.0"));
grid.add(Cell::from("2023-02-20"));

println!("{}", grid.fit_into_console(80).unwrap());

自定义表格样式

use uutils_term_grid::{Grid, GridOptions, Direction, Filling, Cell};

let options = GridOptions {
    direction: Direction::TopToBottom,
    filling: Filling::Text(" | ".to_string()),
};

let mut grid = Grid::new(options);

grid.add(Cell::from("ID"));
grid.add(Cell::from("1"));
grid.add(Cell::from("2"));

grid.add(Cell::from("Name"));
grid.add(Cell::from("Alice"));
grid.add(Cell::from("Bob"));

println!("{}", grid.fit_into_console(40).unwrap());

处理多行文本

use uutils_term_grid::{Grid, GridOptions, Direction, Filling, Cell};

let mut grid = Grid::new(GridOptions::default());

grid.add(Cell::from("Description"));
grid.add(Cell::from("This is a\nmulti-line\ndescription"));

grid.add(Cell::from("Status"));
grid.add(Cell::from("Active"));

println!("{}", grid.fit_into_console(60).unwrap());

高级配置

GridOptions提供了多种配置选项:

  • direction: 控制填充方向 (LeftToRightTopToBottom)
  • filling: 设置单元格间的填充(空格或自定义文本)
  • width: 设置表格总宽度(可选)

Cell结构体也支持多种方法:

  • with_alignment(): 设置对齐方式
  • with_padding(): 设置内边距
  • with_width(): 强制设置宽度

完整示例代码

use uutils_term_grid::{Grid, GridOptions, Direction, Filling, Cell, Alignment};

fn main() {
    // 示例1: 基本表格
    basic_table();
    
    // 示例2: 对齐控制
    alignment_control();
    
    // 示例3: 自定义样式
    custom_style();
    
    // 示例4: 多行文本处理
    multiline_text();
}

fn basic_table() {
    println!("\n=== 基本表格示例 ===");
    
    let mut grid = Grid::new(GridOptions {
        direction: Direction::LeftToRight,
        filling: Filling::Spaces(1),
    });

    // 表头
    grid.add(Cell::from("产品名称"));
    grid.add(Cell::from("价格"));
    grid.add(Cell::from("库存"));

    // 数据行
    grid.add(Cell::from("笔记本电脑"));
    grid.add(Cell::from("5999"));
    grid.add(Cell::from("120"));

    grid.add(Cell::from("智能手机"));
    grid.add(Cell::from("3999"));
    grid.add(Cell::from("85"));

    println!("{}", grid.fit_into_console(80).unwrap());
}

fn alignment_control() {
    println!("\n=== 对齐控制示例 ===");
    
    let mut grid = Grid::new(GridOptions {
        direction: Direction::LeftToRight,
        filling: Filling::Spaces(2),
    });

    // 设置不同对齐方式
    grid.add(Cell::from("项目").with_alignment(Alignment::Left));
    grid.add(Cell::from("预算").with_alignment(Alignment::Right));
    grid.add(Cell::from("进度").with_alignment(Alignment::Center));

    // 数据行
    grid.add(Cell::from("前端开发"));
    grid.add(Cell::from("12000"));
    grid.add(Cell::from("75%"));

    grid.add(Cell::from("后端开发"));
    grid.add(Cell::from("15000"));
    grid.add(Cell::from("60%"));

    println!("{}", grid.fit_into_console(80).unwrap());
}

fn custom_style() {
    println!("\n=== 自定义样式示例 ===");
    
    let options = GridOptions {
        direction: Direction::TopToBottom,
        filling: Filling::Text(" | ".to_string()),
    };

    let mut grid = Grid::new(options);

    // 垂直方向排列的数据
    grid.add(Cell::from("ID"));
    grid.add(Cell::from("101"));
    grid.add(Cell::from("102"));

    grid.add(Cell::from("用户名"));
    grid.add(Cell::from("user1"));
    grid.add(Cell::from("user2"));

    println!("{}", grid.fit_into_console(40).unwrap());
}

fn multiline_text() {
    println!("\n=== 多行文本处理示例 ===");
    
    let mut grid = Grid::new(GridOptions::default());

    grid.add(Cell::from("错误信息"));
    grid.add(Cell::from("无法连接到数据库\n错误代码: 0x45A2\n请检查网络连接"));

    grid.add(Cell::from("状态"));
    grid.add(Cell::from("严重"));

    println!("{}", grid.fit_into_console(60).unwrap());
}

实际应用场景

  1. 命令行工具的输出格式化
  2. 数据报告的终端展示
  3. 调试信息的整齐排列
  4. 日志信息的结构化显示

这个库特别适合需要将结构化数据以美观方式展示给终端用户的Rust应用程序。

回到顶部