You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kev/Drawer/AI/Utils/CsvPreviewHelper.cs

92 lines
2.8 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using AI.Models.SpecialMessages;
namespace AI.Utils
{
/// <summary>
/// CSV 文件解析与预览表格构建
/// </summary>
public static class CsvPreviewHelper
{
/// <summary>
/// 从 CSV 文件路径读取并构建预览表格消息,最多显示指定行数。
/// </summary>
/// <param name="path">CSV 文件路径</param>
/// <param name="maxPreviewRows">最多预览行数,默认 20</param>
/// <param name="title">表格标题,默认「散点文件预览」</param>
/// <returns>成功返回 TableDataMessage失败返回 null</returns>
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<IEnumerable<string>>();
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;
}
/// <summary>
/// 简单解析 CSV 行:按逗号拆分,去除首尾空白,不处理引号内逗号。
/// </summary>
public static List<string> ParseCsvLine(string line)
{
if (string.IsNullOrEmpty(line))
return new List<string>();
return line.Split(',').Select(c => c.Trim()).ToList();
}
}
}