using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using AI.Models.SpecialMessages;
namespace AI.Utils
{
///
/// CSV 文件解析与预览表格构建
///
public static class CsvPreviewHelper
{
///
/// 从 CSV 文件路径读取并构建预览表格消息,最多显示指定行数。
///
/// CSV 文件路径
/// 最多预览行数,默认 20
/// 表格标题,默认「散点文件预览」
/// 成功返回 TableDataMessage,失败返回 null
public static TableDataMessage? TryBuildCsvPreviewTable(string path, int maxPreviewRows = 20, string title = "散点文件预览")
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
return null;
string[] lines;
try
{
lines = File.ReadAllLines(path, Encoding.UTF8);
}
catch
{
try
{
lines = File.ReadAllLines(path);
}
catch
{
return null;
}
}
if (lines.Length == 0)
{
return null;
}
var columnNames = ParseCsvLine(lines[0]);
if (columnNames.Count == 0)
{
return null;
}
var table = new TableDataMessage
{
Title = title,
MaxPreviewRows = maxPreviewRows,
};
var dataRows = new List>();
for (int i = 1; i < lines.Length && dataRows.Count < maxPreviewRows; i++)
{
var cells = ParseCsvLine(lines[i]);
while (cells.Count < columnNames.Count)
{
cells.Add(string.Empty);
}
if (cells.Count > columnNames.Count)
{
cells = cells.Take(columnNames.Count).ToList();
}
dataRows.Add(cells);
}
int totalRowCount = lines.Length - 1;
table.SetData(columnNames, dataRows, totalRowCount);
return table;
}
///
/// 简单解析 CSV 行:按逗号拆分,去除首尾空白,不处理引号内逗号。
///
public static List ParseCsvLine(string line)
{
if (string.IsNullOrEmpty(line))
return new List();
return line.Split(',').Select(c => c.Trim()).ToList();
}
}
}