CLI表格格式化器Skill cli-table-formatter

CLI表格格式化器是一个用于在命令行界面中生成美观、结构化表格的工具。它支持多种边框样式(简单、Unicode、Markdown)、列对齐(左中右)、响应式宽度调整、多行单元格处理和自定义格式化功能。适用于命令行工具开发、监控仪表盘、数据展示等场景,能够显著提升CLI应用的用户体验和数据可读性。关键词:CLI表格格式化、命令行界面、表格输出、数据可视化、TypeScript工具、终端美化、响应式表格、Unicode边框、列对齐、多行单元格。

后端开发 0 次安装 0 次浏览 更新于 2/23/2026

名称: cli-table-formatter 描述: 为结构化CLI输出生成表格格式化器,支持列对齐、边框和响应式尺寸调整。 允许工具: Read, Write, Edit, Bash, Glob, Grep

CLI表格格式化器

为结构化CLI输出生成表格格式化器。

功能

  • 创建多种风格的表格格式化器
  • 配置列对齐和宽度
  • 实现响应式表格尺寸调整
  • 支持Unicode边框
  • 处理多行单元格
  • 生成表格实用工具

使用场景

当您需要时调用此技能:

  • 在CLI中显示表格数据
  • 创建格式化列表输出
  • 配置列宽
  • 支持各种边框样式

输入参数

参数 类型 必填 描述
language 字符串 目标语言
style 字符串 边框样式(simple, unicode, markdown)
features 数组 所需功能

生成模式

TypeScript表格格式化器

import chalk from 'chalk';

export interface TableColumn {
  key: string;
  header: string;
  width?: number;
  align?: 'left' | 'center' | 'right';
  format?: (value: any) => string;
}

export interface TableOptions {
  columns: TableColumn[];
  borderStyle?: 'simple' | 'unicode' | 'none' | 'markdown';
  headerColor?: (text: string) => string;
  maxWidth?: number;
}

const borders = {
  simple: {
    top: '-', bottom: '-', left: '|', right: '|',
    topLeft: '+', topRight: '+', bottomLeft: '+', bottomRight: '+',
    horizontal: '-', vertical: '|', cross: '+',
  },
  unicode: {
    top: '─', bottom: '─', left: '│', right: '│',
    topLeft: '┌', topRight: '┐', bottomLeft: '└', bottomRight: '┘',
    horizontal: '─', vertical: '│', cross: '┼',
    midLeft: '├', midRight: '┤', topMid: '┬', bottomMid: '┴',
  },
  none: {
    top: '', bottom: '', left: '', right: '',
    topLeft: '', topRight: '', bottomLeft: '', bottomRight: '',
    horizontal: '', vertical: '  ', cross: '',
  },
};

export class TableFormatter {
  private columns: TableColumn[];
  private options: TableOptions;
  private border: typeof borders.unicode;

  constructor(options: TableOptions) {
    this.options = options;
    this.columns = options.columns;
    this.border = borders[options.borderStyle || 'unicode'];
  }

  private calculateWidths(data: Record<string, any>[]): number[] {
    return this.columns.map(col => {
      const headerWidth = col.header.length;
      const maxDataWidth = Math.max(
        ...data.map(row => String(row[col.key] ?? '').length)
      );
      return col.width || Math.max(headerWidth, maxDataWidth);
    });
  }

  private padCell(text: string, width: number, align: 'left' | 'center' | 'right' = 'left'): string {
    const padding = width - text.length;
    if (align === 'center') {
      const left = Math.floor(padding / 2);
      const right = padding - left;
      return ' '.repeat(left) + text + ' '.repeat(right);
    }
    if (align === 'right') {
      return ' '.repeat(padding) + text;
    }
    return text + ' '.repeat(padding);
  }

  format(data: Record<string, any>[]): string {
    const widths = this.calculateWidths(data);
    const lines: string[] = [];
    const b = this.border;

    // 顶部边框
    if (b.top) {
      lines.push(
        b.topLeft +
        widths.map(w => b.top.repeat(w + 2)).join(b.topMid || b.cross) +
        b.topRight
      );
    }

    // 表头
    const headerCells = this.columns.map((col, i) =>
      ' ' + this.padCell(col.header, widths[i], col.align) + ' '
    );
    const headerColor = this.options.headerColor || chalk.bold;
    lines.push(
      b.left +
      headerCells.map(c => headerColor(c)).join(b.vertical) +
      b.right
    );

    // 表头分隔线
    if (b.horizontal) {
      lines.push(
        (b.midLeft || b.left) +
        widths.map(w => b.horizontal.repeat(w + 2)).join(b.cross) +
        (b.midRight || b.right)
      );
    }

    // 数据行
    for (const row of data) {
      const cells = this.columns.map((col, i) => {
        const value = row[col.key] ?? '';
        const formatted = col.format ? col.format(value) : String(value);
        return ' ' + this.padCell(formatted, widths[i], col.align) + ' ';
      });
      lines.push(b.left + cells.join(b.vertical) + b.right);
    }

    // 底部边框
    if (b.bottom) {
      lines.push(
        b.bottomLeft +
        widths.map(w => b.bottom.repeat(w + 2)).join(b.bottomMid || b.cross) +
        b.bottomRight
      );
    }

    return lines.join('
');
  }
}

// 快速表格函数
export function table(
  data: Record<string, any>[],
  columns?: (string | TableColumn)[]
): string {
  const cols: TableColumn[] = columns
    ? columns.map(c => typeof c === 'string' ? { key: c, header: c } : c)
    : Object.keys(data[0] || {}).map(key => ({ key, header: key }));

  return new TableFormatter({ columns: cols }).format(data);
}

使用示例

// 简单表格
console.log(table([
  { name: 'Alice', age: 30, role: 'Admin' },
  { name: 'Bob', age: 25, role: 'User' },
]));

// 自定义列
const formatter = new TableFormatter({
  columns: [
    { key: 'id', header: 'ID', width: 6, align: 'right' },
    { key: 'name', header: 'Name', width: 20 },
    { key: 'status', header: 'Status', format: (v) =>
      v === 'active' ? chalk.green(v) : chalk.red(v)
    },
  ],
  borderStyle: 'unicode',
  headerColor: chalk.cyan.bold,
});

console.log(formatter.format(data));

依赖项

{
  "dependencies": {
    "chalk": "^5.0.0"
  }
}

目标流程

  • cli-output-formatting
  • dashboard-monitoring-tui
  • cli-application-bootstrap