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

C# VS2019下平面文件数据行转列生成HTML表格实现方案咨询

实现思路

核心逻辑是先把原始平面文件按行读取、按制表符拆分后存入二维集合,再通过坐标互换完成矩阵转置,根据你的需求可选两种实现路径:

  • 若最终仅需要转置后的DataTable,可直接构造无需依赖Customer类,实现最简单
  • 若必须使用已定义的Customer类存储数据,可通过反射动态匹配ColumnX属性赋值,完全避免硬编码
代码实现

前置步骤:读取原始文件

先将tab分隔的原始文件读取为二维字符串集合,同时限制最多取50行样本:

// 读取原始文件,按行拆分字段
List<List<string>> rawRows = new List<List<string>>();
foreach (string line in File.ReadAllLines(@"你的文件路径").Take(50))
{
    rawRows.Add(line.Split('\t').ToList());
}
if (rawRows.Count == 0) return;

int originalRowCount = rawRows.Count;
int originalColCount = rawRows[0].Count;

方案一:直接生成转置后的DataTable(推荐)

无需依赖自定义Customer类,一步生成可直接转HTML的DataTable:

DataTable transposedDt = new DataTable();
// 转置后列数等于原始行数,列名按ColumnX规则生成
for (int i = 0; i < originalRowCount; i++)
{
    transposedDt.Columns.Add($"Column{i + 1}", typeof(string));
}

// 转置后行数等于原始列数
for (int colIndex = 0; colIndex < originalColCount; colIndex++)
{
    DataRow newRow = transposedDt.NewRow();
    for (int rowIndex = 0; rowIndex < originalRowCount; rowIndex++)
    {
        // 兼容部分行字段不足的边界场景
        newRow[rowIndex] = colIndex < rawRows[rowIndex].Count ? rawRows[rowIndex][colIndex] : string.Empty;
    }
    transposedDt.Rows.Add(newRow);
}

方案二:转置后赋值到自定义Customer类

通过反射动态给ColumnX属性赋值,无需硬写每个属性的赋值逻辑:

List<Customer> customerList = new List<Customer>();
// 提前缓存Customer类的所有Column属性,按序号排序
var columnProps = typeof(Customer)
    .GetProperties()
    .Where(p => p.Name.StartsWith("Column"))
    .OrderBy(p => int.Parse(p.Name.Replace("Column", "")))
    .ToList();

for (int colIndex = 0; colIndex < originalColCount; colIndex++)
{
    Customer customer = new Customer();
    for (int rowIndex = 0; rowIndex < originalRowCount; rowIndex++)
    {
        // 超过定义的属性上限时终止赋值
        if (rowIndex >= columnProps.Count) break;
        string value = colIndex < rawRows[rowIndex].Count ? rawRows[rowIndex][colIndex] : string.Empty;
        columnProps[rowIndex].SetValue(customer, value);
    }
    customerList.Add(customer);
}
补充说明
  • 两种方案都兼容5-15列的浮动列数场景,只要Customer类的Column属性数量不低于50个就能覆盖需求
  • 若后续不需要Customer类做其他业务处理,优先选择方案一,性能更好且无需维护属性反射逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:45:00