C# 中使用 Spectre.Console 创建美观的数据表格

56 阅读7分钟

前言

在命令行应用程序开发中,如何让数据展示既清晰又美观一直是一个挑战。Spectre.Console 是一个功能强大的 .NET 库,专为提升控制台应用的用户体验而设计。它不仅支持丰富的文本格式化功能,还提供了灵活且易于使用的表格组件,帮助大家以结构化的方式展示数据。

本文将详细介绍如何使用 Spectre.Console 创建和自定义表格,让控制台应用也能拥有媲美图形界面的数据展示效果。

一、基础表格的创建与配置

Spectre.Console 的表格系统设计智能,能够根据内容自动调整列宽,确保表格在终端中显示整洁、易读。

1、安装 Spectre.Console 包

首先,在项目目录下通过 NuGet 安装 Spectre.Console:

dotnet add package Spectre.Console

2、引入命名空间

在代码文件顶部引入命名空间,以便使用相关类和方法:

using Spectre.Console;

3、创建并渲染基本表格

以下是创建一个简单表格的基本步骤:

// 创建一个新的表格对象
var table = new Table();

// 添加表格标题
table.Title("[blue]用户信息表[/]");

// 添加列
table.AddColumn("姓名");
table.AddColumn("年龄");
table.AddColumn("邮箱");

// 添加行数据
table.AddRow("张三", "28", "zhangsan@example.com");
table.AddRow("李四", "32", "lisi@example.com");
table.AddRow("王五", "25", "wangwu@example.com");

// 渲染表格到控制台
AnsiConsole.Render(table);

这段代码会在控制台中渲染一个包含三列三行的表格,展示产品信息。

表格基本配置

Spectre.Console 提供了多种方法来配置表格的整体行为:

// 无边框  
table.Border(TableBorder.None);  

// ASCII边框  
table.Border(TableBorder.Ascii);  

// 方形边框  
table.Border(TableBorder.Square);  

// 圆角边框  
table.Border(TableBorder.Rounded);    

表格样式定制与边框设置

边框样式

Spectre.Console 提供了多种边框样式选项:

// 无边框  table.Border(TableBorder.None);  // ASCII边框  table.Border(TableBorder.Ascii);  // 方形边框  table.Border(TableBorder.Square);  // 圆角边框  table.Border(TableBorder.Rounded);  

表格对齐方式

表格整体的对齐方式可以通过以下方法设置:

using Spectre.Console;

namespace AppTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            // 创建表格实例  
            var table = new Table();

            // 添加列  
            table.AddColumn("产品名称");
            table.AddColumn("价格");
            table.AddColumn("库存数量");

            // 添加行  
            table.AddRow("笔记本电脑", "¥599", "23");
            table.AddRow("机械键盘", "¥299", "45");
            table.AddRow("无线鼠标", "¥129", "67");

            // 圆角边框  
            table.Border(TableBorder.Rounded);

            // 设置第一列右对齐  
            table.Columns[0].Alignment(Justify.Right);
            table.Columns[0].RightAligned();

            // 设置第二列居中对齐  
            table.Columns[1].Centered();

            // 设置第三列左对齐  
            table.Columns[2].LeftAligned();

            // 渲染表格到控制台  
            AnsiConsole.Write(table);

            Console.ReadKey();
        }
    }
}

表格内容格式化

列格式化与对齐

每一列都可以单独设置对齐方式:

// 设置第一列右对齐  
table.Columns[0].Alignment(Justify.Right);  
table.Columns[0].RightAligned();  

// 设置第二列居中对齐  
table.Columns[1].Centered();  

// 设置第三列左对齐  
table.Columns[2].LeftAligned();  

内容填充与宽度

可以对列的内容填充和宽度进行精确控制:

using Spectre.Console;

namespace AppTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            // 创建表格实例  
            var table = new Table();

            // 添加列  
            table.AddColumn("产品名称");
            table.AddColumn("价格");
            table.AddColumn("库存数量");

            // 添加行  
            table.AddRow("笔记本电脑", "¥599", "23");
            table.AddRow("机械键盘", "¥299", "45");
            table.AddRow("无线鼠标", "¥129", "67");

            // 设置第一列左侧填充3个字符,右侧填充5个字符  
            table.Columns[0].PadLeft(3).PadRight(5);

            // 如果左右填充相同,可以使用简写方式  
            table.Columns[1].Padding(4, 0); // 水平填充4个字符,垂直填充被忽略  

            // 设置第二列宽度为15个字符  
            table.Columns[1].Width(15);

            // 禁止第三列内容换行  
            table.Columns[2].NoWrap();

            // 渲染表格到控制台  
            AnsiConsole.Write(table);

            Console.ReadKey();
        }
    }
}

使用样式标记

Spectre.Console 支持富文本标记语言,可以在表格内容中使用:

table.AddRow("笔记本电脑""[green]¥5999[/]""[bold]23[/]");

多行内容与单元格合并

多行内容

Spectre.Console 允许在单元格中显示多行内容,可以使用各种渲染对象作为单元格内容:

using Spectre.Console;
using System;
using System.Text;

namespace AppTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            // 创建表格实例
            var table = new Table();

            // 设置表格边框和样式以增强可读性
            table.Border(TableBorder.Rounded);
            table.Expand();

            // 添加列
            table.AddColumn(new TableColumn("产品名称").Width(20));
            table.AddColumn(new TableColumn("价格").Width(10).RightAligned());
            table.AddColumn(new TableColumn("库存数量").Width(10).Centered());

            // 添加行
            table.AddRow("笔记本电脑", "¥599", "23");
            table.AddRow("机械键盘", "¥299", "45");
            table.AddRow("无线鼠标", "¥129", "67");

            // 创建一个面板作为单元格内容
            var productDetails = new Panel("品牌: 戴尔\n型号: XPS 13\n颜色: 银色");
            productDetails.Border = BoxBorder.Rounded;

            // 将面板添加到表格单元格
            table.AddRow(productDetails);

            // 渲染表格到控制台
            AnsiConsole.Write(table);

            Console.ReadKey();
        }
    }
}

嵌套表格

Spectre.Console 强大的功能之一是支持在单元格中嵌套其他可渲染对象,包括另一个表格:

// 创建一个嵌套表格  
var specTable = new Table();
specTable.AddColumn("参数");
specTable.AddColumn("规格");
specTable.AddRow("CPU", "Intel i7");
specTable.AddRow("内存", "16GB");
specTable.AddRow("存储", "512GB SSD");
specTable.Border(TableBorder.Simple);

// 将嵌套表格添加到主表格的单

案例:开发一个产品库存信息表格展示系统

下面我们将开发一个简单的产品库存信息表格展示系统,用于展示产品信息并输出为Markdown格式。

产品类定义

首先,定义一个产品类:

public class Product  
{  
    public string Name { get; set; }  
    public decimal Price { get; set; }  
    public int StockQuantity { get; set; }  
    public string Category { get; set; }  
    public string Description { get; set; }  
}  

创建产品库存表格

using Spectre.Console;
using System;
using System.Text;

namespace AppTable
{
    publicclass Product
    {
        publicstring Name { get; set; }
        public decimal Price { get; set; }
        publicint StockQuantity { get; set; }
        publicstring Category { get; set; }
        publicstring Description { get; set; }
    }
    publicclass InventorySystem
    {
        private List<Product> _products;

        public InventorySystem()
        {
            _products = new List<Product>
        {
            new Product { Name = "ThinkPad X1", Price = 8999, StockQuantity = 15, Category = "笔记本电脑", Description = "轻薄商务本" },
            new Product { Name = "机械键盘", Price = 349.99M, StockQuantity = 50, Category = "配件", Description = "Cherry轴体" },
            new Product { Name = "无线鼠标", Price = 129.99M, StockQuantity = 100, Category = "配件", Description = "高精度传感器" },
            new Product { Name = "27寸显示器", Price = 1299, StockQuantity = 20, Category = "显示设备", Description = "4K HDR" },
            new Product { Name = "电脑包", Price = 199, StockQuantity = 35, Category = "配件", Description = "防水耐磨" }
        };
        }

        public void DisplayInventory()
        {
            var table = new Table();

            // 设置表格样式  
            table.Border(TableBorder.Rounded);
            table.Expand();
            table.Title("[bold]产品库存信息[/]");

            // 添加列  
            table.AddColumn(new TableColumn("产品名称").Centered());
            table.AddColumn(new TableColumn("价格(¥)").RightAligned());
            table.AddColumn(new TableColumn("库存数量").Centered());
            table.AddColumn(new TableColumn("分类").LeftAligned());
            table.AddColumn(new TableColumn("描述").LeftAligned());

            // 添加行  
            foreach (var product in _products)
            {
                string priceStr = product.Price.ToString("F2");
                string stockColor = product.StockQuantity < 20 ? "red" : (product.StockQuantity < 50 ? "yellow" : "green");

                table.AddRow(
                    product.Name,
                    priceStr,
                    $"[{stockColor}]{product.StockQuantity}[/]",
                    product.Category,
                    product.Description
                );
            }

            // 显示表格  
            AnsiConsole.Write(table);

            // 输出Markdown  
            Console.WriteLine("\n生成的Markdown表格:\n");
            Console.WriteLine(ConvertToMarkdown(table));
        }

        public string ConvertToMarkdown(Table table)
        {
            var markdown = new StringBuilder();

            // 添加标题  
            markdown.AppendLine("# 产品库存信息");
            markdown.AppendLine();

            // 添加表头  
            markdown.Append("| 产品名称 | 价格(¥) | 库存数量 | 分类 | 描述 |");
            markdown.AppendLine();

            // 添加分隔行  
            markdown.Append("| :---: | ---: | :---: | :--- | :--- |");
            markdown.AppendLine();

            // 添加数据行  
            foreach (var product in _products)
            {
                markdown.AppendLine($"| {product.Name} | {product.Price:F2} | {product.StockQuantity} | {product.Category} | {product.Description} |");
            }

            return markdown.ToString();
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            var system = new InventorySystem();
            system.DisplayInventory();
            Console.ReadKey();
        }
    }
}

总结

Spectre.Console 提供了强大而灵活的表格功能,是 .NET 开发在控制台应用中展示结构化数据的理想选择。本文介绍了如何创建基础表格、自定义样式、格式化内容以及实现嵌套表格等高级功能,并通过一个产品库存展示的案例演示了其实际应用。

除了表格,Spectre.Console 还提供了面板、进度条、树形结构等多种 UI 组件,帮助开发者打造美观且交互性强的命令行界面。

掌握 Spectre.Console,将提升开发控制台应用的专业度与用户体验。

最后

如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。

也可以加入微信公众号 [DotNet技术匠] 社区,与其他热爱技术的同行一起交流心得,共同成长!

优秀是一种习惯,欢迎大家留言学习!

作者:技术老小子

出处:mp.weixin.qq.com/s/7wCXJTAam1M2xRD5ly5ZTg

声明:网络内容,仅供学习,尊重版权,侵权速删,歉意致谢!