读取CSV文件在c#和存储在DataTable

本文关键字:存储 DataTable 文件 读取 CSV | 更新日期: 2023-09-27 17:52:34

我使用以下代码读取csv文件并存储到c#中。但我的要求是,我想跳过csv文件中的第一行,因为它不是结构化的,因此将第二行作为列。如何在现有代码中做到这一点。

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{    
   DataTable csvData = new DataTable();
    try
    {
    using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[] { ";" });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();
            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }
            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == "")
                    {
                        fieldData[i] = null;
                    }
                 }
                     csvData.Rows.Add(fieldData);
             }
        }
   }
   catch (Exception ex)
   {
   }
   return csvData;
}

我的CSV文件看起来像

a;;{b;g;t{}
firstname;lastname;age;locaion
peter;vela;28;denver
sasi;kiran;38;colorado
sastri;miro;texas

读取CSV文件在c#和存储在DataTable

TextFieldParser类有一个可以接收流的构造函数。
所以这个想法是:在你的文件上打开一个StreamReader,读取第一行并丢弃它,然后用打开的StreamReader在你的列名存在的第二行上构建TextFieldParser。

我已经测试了它,它似乎工作

using (StreamReader reader = new StreamReader(csv_file_path))
{
    // Discard the first line... (add checking here)
    reader.ReadLine();
    using(TextFieldParser csvReader = new TextFieldParser(reader))
    {
       csvReader.SetDelimiters(new string[] { ";" });
       .....

我还根据示例数据将分隔符设置为分号而不是逗号。

应该可以:

int rowsToSkip = 1;
int position = 0;
while (!csvReader.EndOfData)
{
    string[] fieldData = csvReader.ReadFields();
    if(position >= rowsToSkip)
    {
        //Making empty value as null
        for (int i = 0; i < fieldData.Length; i++)
        {
            if (fieldData[i] == "")
            {
                fieldData[i] = null;
            }
        }
        csvData.Rows.Add(fieldData);
    }
    position++;
}

如果你想让你的生活更轻松,准备好花钱。Flexcel将使您的生活更轻松。

这将在两行代码中完成。

谢谢

string[] Lines = File.ReadAllLines(this.INPUTTFILE);

            string[] Fields;
            for (int i = 1; i < Lines.GetLength(0); i++)
            {
                DataRow Row = Dt_Input_With_ColoumName.NewRow();
                Fields = Lines[i].Split(new char[] { ',' });
                for (int f = 0; f < Dt_Input_With_ColoumName.Columns.Count; f++)
                {
                    Row[f] = Fields[f];
                }
                Dt_Input_With_ColoumName.Rows.Add(Row);
            }