C# 读取CSV文件中的某一行解决思路
C# 读取CSV文件中的某一行
我现在有一个CSV文件,要把它读取出来,但是这个CSV文件的前面2行是没用的数据,我想把第3行当成标题列来读取,有什么可用的方法
我现在有一个CSV文件,要把它读取出来,但是这个CSV文件的前面2行是没用的数据,我想把第3行当成标题列来读取,有什么可用的方法
private List<Dictionary<string, string>> ConvertFileToDic(string fileName)
{
char delimiter = ',';
CsvReader reader = null;
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
StreamReader sReader = null;
//读取CSV
sReader = new StreamReader(fileName, Encoding.Unicode);
using (reader = new CsvReader(sReader, true, delimiter))
{
reader.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;
//保证是使用正确的分隔符
int fieldCount = 0;
try
{
fieldCount = reader.FieldCount;
}
catch (Exception)
{
sReader = new StreamReader(fileName, Encoding.Unicode);
reader = new CsvReader(sReader, true, delimiter == '\t' ? ',' : '\t');
fieldCount = reader.FieldCount;
}
if (reader.FieldCount <= 1)
{
sReader = new StreamReader(fileName, Encoding.Unicode);
reader = new CsvReader(sReader, true, delimiter == '\t' ? ',' : '\t');
fieldCount = reader.FieldCount;
}
//CSV标题
string[] headers = reader.GetFieldHeaders();
while (reader.ReadNextRecord())
{
Dictionary<string, string> dic = new Dictionary<string, string>();
try
{
for (int i = 0; i < headers.Length; i++)
{
dic[headers[i]] = reader[i];
}
}
catch (Exception)