读取csv行时C#获取相应的行标题值 [英] C# while reading csv rows get the corresponding row header value
本文介绍了读取csv行时C#获取相应的行标题值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用TextFieldParser阅读csv。但是我需要帮助才能在读取行时获取当前行标题文本。这是我的代码。请帮助
我尝试过:
i have tried reading the csv using TextFieldParser. However i need help to get the current row header text while reading the rows.this is my code.Please help
What I have tried:
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System;
using Microsoft.VisualBasic.FileIO;
namespace DataTableTeste
{
class Program
{
static void Main(string[] args)
{
string csv_file_path = @"C:\Users\MEI.csv";
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
List<int> coulumnNamelist = new List<int>();
for (int index = 0; index < colFields.Length; index++)
{
string column = colFields[index];
coulumnNamelist.Add(index);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
for (int i = 0; i < fieldData.Length; i++)
{
// here i need to get the coulmn header
}
}
}
}
}
}
推荐答案
List<int> coulumnNamelist = new List<int>();
for (int index = 0; index < colFields.Length; index++)
{
string column = colFields[index];
coulumnNamelist.Add(index);
}
该块只会创建一个容易混淆的列索引列表。您可以安全地删除它。
列标题存储在 colFields
数组中。您可以使用它来读取标题:
That block just creates a confusingly-named list of the column indices. You can safely remove that.
The column headers are stored in the colFields
array. You can use that to read the headers:
string[] fieldData = csvReader.ReadFields();
for (int i = 0; i < fieldData.Length; i++)
{
string columnHeader = colFields[i];
...
}
由于行标题通常/始终是第一条记录,因此您读取该记录,保存然后继续阅读数据。
在标题上使用string.split来获取列名。
Since the "row header" is usually / always the first record, you read that record, save it, and then proceed to read the "data".
Use string.split on the header to get the "column names".
这篇关于读取csv行时C#获取相应的行标题值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文