Rust表格渲染库nu-table的使用,为命令行和终端应用提供美观的表格格式化功能
Rust表格渲染库nu-table的使用,为命令行和终端应用提供美观的表格格式化功能
nu-table是Nushell项目中的一个内部库,主要用于实现表格视图的布局逻辑。虽然它主要是为Nushell内部使用而设计,但也可以用于其他Rust命令行和终端应用中。
安装
在项目目录中运行以下Cargo命令:
cargo add nu-table
或者在Cargo.toml中添加:
nu-table = "0.106.1"
基本使用示例
下面是一个使用nu-table在命令行中渲染表格的完整示例:
use nu_table::{Table, TableConfig};
use std::collections::HashMap;
fn main() {
// 创建表格数据
let mut data = Vec::new();
let mut row1 = HashMap::new();
row1.insert("Name".to_string(), "Alice".to_string());
row1.insert("Age".to_string(), "25".to_string());
row1.insert("Occupation".to_string(), "Engineer".to_string());
data.push(row1);
let mut row2 = HashMap::new();
row2.insert("Name".to_string(), "Bob".to_string());
row2.insert("Age".to_string(), "30".to_string());
row2.insert("Occupation".to_string(), "Designer".to_string());
data.push(row2);
let mut row3 = HashMap::new();
row3.insert("Name".to_string(), "Charlie".to_string());
row3.insert("Age".to_string(), "35".to_string());
row3.insert("Occupation".to_string(), "Manager".to_string());
data.push(row3);
// 配置表格
let config = TableConfig {
theme: nu_table::Theme::basic(), // 使用基本主题
..Default::default()
};
// 创建并渲染表格
let table = Table::new(data, config);
println!("{}", table.render());
}
高级配置示例
nu-table提供了多种配置选项来控制表格的外观:
use nu_table::{Table, TableConfig, TextStyle};
fn main() {
// 创建更复杂的数据
let mut data = vec![
vec!["Product".to_string(), "Price".to_string(), "Stock".to_string()],
vec!["Laptop".to_string(), "$999".to_string(), "15".to_string()],
vec!["Phone".to_string(), "$699".to_string(), "32".to_string()],
vec!["Tablet".to_string(), "$499".to_string(), "25".to_string()],
];
// 高级配置
let config = TableConfig {
theme: nu_table::Theme::rounded(), // 使用圆角边框主题
header_style: Some(TextStyle::new().bold(true).fg(nu_table::Color::Blue)),
align_header: nu_table::Alignment::Center,
align_content: nu_table::Alignment::Right,
..Default::default()
};
// 创建并渲染表格
let table = Table::new(data, config);
println!("{}", table.render());
}
完整示例demo
以下是结合基本和高级功能的完整示例,展示如何使用nu-table创建带有自定义样式的表格:
use nu_table::{Table, TableConfig, TextStyle, Alignment, Color};
use std::collections::HashMap;
fn main() {
// 创建表格数据 - 使用HashMap表示每行数据
let mut data = Vec::new();
// 第一行数据
let mut row1 = HashMap::new();
row1.insert("ID".to_string(), "1".to_string());
row1.insert("Name".to_string(), "Alice".to_string());
row1.insert("Score".to_string(), "95".to_string());
row1.insert("Status".to_string(), "Passed".to_string());
data.push(row1);
// 第二行数据
let mut row2 = HashMap::new();
row2.insert("ID".to_string(), "2".to_string());
row2.insert("Name".to_string(), "Bob".to_string());
row2.insert("Score".to_string(), "88".to_string());
row2.insert("Status".to_string(), "Passed".to_string());
data.push(row2);
// 第三行数据
let mut row3 = HashMap::new();
row3.insert("ID".to_string(), "3".to_string());
row3.insert("Name".to_string(), "Charlie".to_string());
row3.insert("Score".to_string(), "42".to_string());
row3.insert("Status".to_string(), "Failed".to_string());
data.push(row3);
// 高级表格配置
let config = TableConfig {
theme: nu_table::Theme::compact(), // 使用紧凑主题
header_style: Some(
TextStyle::new()
.bold(true)
.fg(Color::Green) // 标题绿色
.underline(true) // 带下划线
),
align_header: Alignment::Center, // 标题居中
align_content: Alignment::Left, // 内容左对齐
trim_whitespace: true, // 修剪空白
..Default::default()
};
// 创建并渲染表格
let table = Table::new(data, config);
println!("学生成绩表:\n{}", table.render());
}
注意事项
- nu-table主要是为Nushell内部使用而设计,可能不适合所有场景
- 该库提供了多种主题和样式选项来定制表格外观
- 可以控制表格的对齐方式、边框样式、文本颜色等
- 表格数据可以使用HashMap或Vec<Vec<String>>格式
- 主题样式包括basic(基本)、rounded(圆角)、compact(紧凑)等
1 回复
Rust表格渲染库nu-table使用指南
nu-table是一个为命令行和终端应用提供美观表格格式化功能的Rust库。它源自流行的nushell项目,现作为独立库供开发者使用。
安装
在Cargo.toml中添加依赖:
[dependencies]
nu-table = "0.2"
基本使用
创建简单表格
use nu_table::{Table, TableTheme};
fn main() {
let mut table = Table::new();
table.set_theme(TableTheme::rounded());
// 添加表头
table.set_header(vec!["Name", "Age", "City"]);
// 添加数据行
table.add_row(vec!["Alice", "28", "New York"]);
table.add_row(vec!["Bob", "32", "London"]);
table.add_row(vec!["Charlie", "24", "Paris"]);
println!("{}", table.render());
}
输出效果
╭─────────┬─────┬──────────╮
│ Name │ Age │ City │
├─────────┼─────┼──────────┤
│ Alice │ 28 │ New York │
│ Bob │ 32 │ London │
│ Charlie │ 24 │ Paris │
╰─────────┴─────┴──────────╯
高级功能
自定义主题
use nu_table::{Table, TableTheme};
fn main() {
let mut table = Table::new();
// 创建自定义主题
let mut theme = TableTheme::rounded();
theme.vertical = '│';
theme.horizontal = '─';
theme.intersection_top = '┬';
table.set_theme(theme);
table.set_header(vec!["ID", "Value"]);
table.add_row(vec!["1", "First"]);
table.add_row(vec!["2", "Second"]);
println!("{}", table.render());
}
对齐方式
use nu_table::{Table, TableTheme, Alignment};
fn main() {
let mut table = Table::new();
table.set_theme(TableTheme::rounded());
table.set_header(vec!["Left", "Center", "Right"]);
// 设置列对齐
table.set_alignments(vec![
Alignment::Left,
Alignment::Center,
Alignment::Right
]);
table.add_row(vec!["A", "B", "C"]);
table.add_row(vec!["Longer text", "Center me", "12345"]);
println!("{}", table.render());
}
颜色支持
use nu_table::{Table, TableTheme};
use nu_ansi_term::{Color, Style};
fn main() {
let mut table = Table::new();
table.set_theme(TableTheme::rounded());
// 设置带颜色的表头
table.set_header(vec![
Style::new().fg(Color::Red).bold().paint("Name").to_string(),
Style::new().fg(Color::Blue).paint("Score").to_string()
]);
table.add_row(vec![
"Alice".to_string(),
Color::Green.paint("95").to_string()
]);
println!("{}", table.render());
}
从数据结构创建表格
use nu_table::{Table, TableTheme};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
city: String,
}
fn main() {
let data = vec![
Person { name: "Alice".into(), age: 28, city: "New York".into() },
Person { name: "Bob".into(), age: 32, city: "London".into() },
];
let mut table = Table::new();
table.set_theme(TableTheme::rounded());
// 从结构体创建表格
table.set_header(vec!["Name", "Age", "City"]);
for person in data {
table.add_row(vec![
person.name,
person.age.to_string(),
person.city
]);
}
println!("{}", table.render());
}
完整示例demo
use nu_table::{Table, TableTheme, Alignment};
use nu_ansi_term::{Color, Style};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Product {
id: u32,
name: String,
price: f64,
in_stock: bool,
}
fn main() {
// 示例数据
let products = vec![
Product { id: 1, name: "Laptop".into(), price: 999.99, in_stock: true },
Product { id: 2, name: "Mouse".into(), price: 24.95, in_stock: true },
Product { id: 3, name: "Keyboard".into(), price: 49.99, in_stock: false },
];
// 创建表格实例
let mut table = Table::new();
table.set_theme(TableTheme::rounded());
// 设置带颜色的表头
table.set_header(vec![
Style::new().fg(Color::Green).bold().paint("ID").to_string(),
Style::new().fg(Color::Blue).bold().paint("Product").to_string(),
Style::new().fg(Color::Yellow).bold().paint("Price").to_string(),
Style::new().fg(Color::Red).bold().paint("Stock").to_string(),
]);
// 设置列对齐方式
table.set_alignments(vec![
Alignment::Center,
Alignment::Left,
Alignment::Right,
Alignment::Center,
]);
// 添加数据行
for product in products {
let stock_status = if product.in_stock {
Color::Green.paint("In Stock").to_string()
} else {
Color::Red.paint("Out of Stock").to_string()
};
table.add_row(vec![
product.id.to_string(),
product.name,
format!("${:.2}", product.price),
stock_status,
]);
}
// 渲染并打印表格
println!("{}", table.render());
}
输出效果
╭────┬──────────┬────────┬─────────────╮
│ ID │ Product │ Price │ Stock │
├────┼──────────┼────────┼─────────────┤
│ 1 │ Laptop │ $999.99│ In Stock │
│ 2 │ Mouse │ $24.95│ In Stock │
│ 3 │ Keyboard │ $49.99│ Out of Stock│
╰────┴──────────┴────────┴─────────────╯
注意事项
- nu-table会自动根据终端宽度调整表格大小
- 支持UTF-8字符和多行文本
- 可以通过
table.set_width()
手动设置表格宽度 - 对于大量数据,考虑分批渲染以提高性能
nu-table是一个功能强大且易于使用的表格渲染库,特别适合需要美观命令行输出的Rust应用程序。