Home » MS OfficeRSS

CSV Reader through code is not reading the first row which contain Headings

Hi,

I'm using C# to get the data from the CSV file. For this, I'm using the following approach.

//Get data from csv fileprivate DataSet GetData(byte[] csvcontent)
    {
      string strLine;
      string[] strArray;
      char[] charArray = newchar[] { ',' };
      DataSet ds = new DataSet();
      DataTable dt = ds.Tables.Add("TheData");
      MemoryStream reader = new MemoryStream(csvcontent);
      StreamReader sr = new StreamReader(reader);

      strLine = sr.ReadLine();

      strArray = strLine.Split(charArray);

      for (int x = 0; x <= strArray.GetUpperBound(0); x++)
      {
        dt.Columns.Add(strArray[x].Trim());
      }

      strLine = sr.ReadLine();
      while (strLine != null)
      {
        strArray = strLine.Split(charArray);
        DataRow dr = dt.NewRow();
        for (int i = 0; i <= strArray.GetUpperBound(0); i++)
        {
          dr[i] = strArray[i].Trim();
        }
        dt.Rows.Add(dr);
        strLine = sr.ReadLine();
      }
      sr.Close();
      return ds;
    }

I'm calling the above function link this:

//Extract data from csv file
              SPFile DocFile = myLibraryItem.File;
              byte[] csvcontent = DocFile.OpenBinary();
              DataSet ds = GetData(csvcontent);
              DataTable dt = ds.Tables[0];

Now, the problem is that it is not reading the first row of the CSV file which contain headings. Anyone has any idea how we can do this ?

Thanks

 

1 Answer Found

 

Answer 1

Looking at the code  I think that it actually does read them, but it doesn't put the headers in as a first row, it uses the heathers to name the columns  in the datatable.

 

It does that here:

   strArray = strLine.Split(charArray);

   for (int x = 0; x <= strArray.GetUpperBound(0); x++)
   {
    dt.Columns.Add(strArray[x].Trim());
   }

Also, you might want to have a look at Linq2CSV, which does what you need, and a couple of other things:

http://www.codeproject.com/KB/linq/LINQtoCSV.aspx?msg=3498795&PageFlow=Fluid

 
 
 

<< Previous      Next >>


Microsoft   |   Windows   |   Visual Studio   |   Follow us on Twitter