You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 控制台应用读取Excel数据后如何实现规整格式化输出

对齐实现核心原理

你当前输出错乱的两个核心问题:

  1. 固定写死列宽为5个字符,无法适配不同长度的单元格内容
  2. 额外拼接了制表符\t,制表符的占位宽度会随当前输出位置动态变化,进一步打乱对齐规则

要实现规整的表格输出,核心逻辑分两步:

  • 预计算列宽:先遍历所有单元格,统计每一列内容的最大长度,作为该列的统一输出宽度(可额外加2个字符作为左右内边距,提升美观度)
  • 按宽格式化:输出时每一列严格按照预计算的宽度做对齐填充,C#内置的String.Format和PadRight/PadLeft方法都支持固定宽度对齐:
    • String.Format("{0,-10}", content):左对齐,占10个字符宽度,不足部分右侧补空格
    • content.PadRight(10):效果和上面的写法完全等效
    • 把固定数值10替换成预计算的对应列宽度,就能实现整列对齐
调整后的可运行代码
using Microsoft.Office.Interop.Excel;
using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        string nfile = Directory.GetCurrentDirectory() + "/Assets.xlsx";
        Program p = new Program();
        p.loadDB(nfile);
    }

    private void loadDB(string file)
    {
        Application excelApp = new Application();

        if (!File.Exists(file))
        {
            Console.WriteLine("File does not exist");
            return;
        }
        if (excelApp == null)
        {
            Console.WriteLine("Excel is not installed");
            return;
        }

        Workbook excelBook = excelApp.Workbooks.Open(file);
        _Worksheet excelSheet = excelBook.Sheets[1];
        Range excelRange = excelSheet.UsedRange;

        int rowCount = excelRange.Rows.Count;
        int colCount = excelRange.Columns.Count;

        // 第一步:遍历所有单元格,计算每列的最大输出宽度
        int[] colWidths = new int[colCount];
        for (int i = 1; i <= rowCount; i++)
        {
            for (int j = 1; j <= colCount; j++)
            {
                var val = (Range)excelRange.Cells[i, j];
                string content = val?.Value2?.ToString() ?? "";
                // 取当前内容长度和历史最大值的较大值,额外加2作为左右内边距
                colWidths[j - 1] = Math.Max(colWidths[j - 1], content.Length + 2);
            }
        }

        // 第二步:按预计算宽度输出表格
        for (int i = 1; i <= rowCount; i++)
        {
            // 表头下方加分隔线
            if (i == 2)
            {
                Console.WriteLine(new string('-', colWidths.Sum() + colCount + 1));
            }
            for (int j = 1; j <= colCount; j++)
            {
                var val = (Range)excelRange.Cells[i, j];
                string content = val?.Value2?.ToString() ?? "";
                // 按对应列的宽度左对齐输出
                Console.Write(String.Format("|{0,-" + colWidths[j-1] + "}", content));
            }
            Console.WriteLine("|");
        }

        excelApp.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        Console.ReadLine();
    }
}
可选优化方向
  • 如果存在超长内容,可以在计算宽度时设置最大上限,超过长度的内容截断加...避免撑破表格
  • 如果需要适配中文等全角字符,可以额外判断字符的全半角,全角字符按2个宽度计算,避免中英文混合排版错位
  • 可以把表格输出逻辑封装为通用工具类,后续其他需要控制台输出表格的场景直接复用

内容的提问来源于stack exchange,提问作者WiRR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:15:03