Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have csv file uploaded by UploadFile control which has no header row. When I try to read it to datatable it gives the error because the first row has same values in different columns. How to insert the header row to this file or read data from csv to datatable with predefined columns



Data in csv:
IO23968 2012 11 AB WI 100162804410W500 0 516.78 0 0 0 N 0
IO24190 2012 11 AB WI 100140604510W500 302 516.78 15617.9 0 15617 N 0
IO24107 2012 11 AB WI 100033104410W500 337 516.78 17456.3 0 17456 N 0



Control:
HtmlInputFile fileOilFile = fileOilSubmission as HtmlInputFile;

if (fileOilFile != null)
strOilFileName = fileOilFile.Value;

DataTable:
DataTable csvData = new DataTable();
csvData.Columns.Add("RoyaltyEntityID", typeof(string));
csvData.Columns.Add("ProductionYear", typeof(int));
csvData.Columns.Add("ProductionMonth", typeof(int));
csvData.Columns.Add("ProductionEntityID", typeof(string));
csvData.Columns.Add("ProductionVolume", typeof(double));
csvData.Columns.Add("SalePrice", typeof(double));
csvData.Columns.Add("GrossRoyaltyAmount", typeof(double));
csvData.Columns.Add("TruckingRate", typeof(double));
csvData.Columns.Add("TotalNetRoyalty", typeof(double));
csvData.Columns.Add("ConfidentialWell", typeof(bool));
csvData.Columns.Add("HoursProductionAmount", typeof(double));



using (StreamReader sr = File.OpenText(strOilFileName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{ //we're just testing read speeds

foreach (var line in strOilFileName)
{
csvData.Rows.Add(line.split(',')[0]);
csvData.Rows.Add(line.split(',')[1]);
csvData.Rows.Add(line.split(',')[2]);
csvData.Rows.Add(line.split(',')[3]);
}
}
}

And Split does not work
Posted
Updated 10-Dec-13 12:04pm
v5

 
Share this answer
 
Comments
Member 10458175 10-Dec-13 17:46pm    
Thank you but could you please give me an example? I'm very junior..
Maciej Los 23-Dec-13 18:17pm    
Try this..

C#
DataRow dr = csvData.NewRow();
using (StreamReader sr = new StreamReader("/file.csv"))
{
      string line = string.Empty;
      while ((line = sr.ReadLine()) != null)
      {
            string[] strRow = line.Split(',');

            dr["RoyaltyEntityID"] = strRow[0];
            dr["ProductionYear"] = strRow[1];
            dr["ProductionMonth"] = strRow[2];
            ...
            csvData.Rows.Add(dr);
      }
}
 
Share this answer
 
v2
Comments
Member 10458175 12-Dec-13 11:50am    
Thanks a lot! it works perfectly.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900