将没有标题行文件的CSV导入数据表

时间:2013-12-10 21:44:29

标签: csv datatable

我有一个由UploadFile控件上传的CSV文件,它没有标题行。当我尝试将其读取到datatable时,它会给出错误,因为第一行在不同的列中具有相同的值。如何将标题行插入此文件或将数据从CSV读取到具有预定义列的数据表?

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]);
            }
          }
        }

3 个答案:

答案 0 :(得分:0)

您是否可以在代码中手动添加标题,然后在解析文件时添加行:

例如:

DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

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

答案 1 :(得分:0)

下面的代码显示了如何将CSV读入DataTable。

此代码假设您的CSV可以在strOilFileName找到,而DataTable的架构就是您在问题中显示的内容。我还假设你的CSV实际上是以逗号分隔的(从问题中的示例数据看起来不那么明显。)

DataTable csvData = new DataTable();
// ... add columns as you show.

using (StreamReader sr = File.OpenText(strOilFileName)) {
    string line = string.Empty;
    while ((line = sr.ReadLine()) != null) {
        string[] fields = line.Split(',');
        if (fields.Length == 13) {
            // Create a new empty row based on your DataTable's schema.
            var row = csvData.NewRow();

            //Start populating the new row with data from the CSV line.    
            row[0] = fields[0];

            // You can't be sure that the data in your CSV can be converted to your DataTable's column's data type so
            // always use the TryParse methods when you can.
            int prodYear = 0;
            if (int.TryParse(fields[1], out prodYear)) {
                row[1] = prodYear;
            } else {
                // Do what when the field's value does not contain a value that can be converted to an int?  
                // Here I'm setting the field to 2000 but you'll want to throw an Exception, set a different default, etc.
                row[1] = 2000;
            }
            //
            // Repeat the above steps for filling the rest of the columns in your DataRow.
            //

            // Add your new row to your DataTable.                        
            csvData.Rows.Add(row);
        } else {
            // Do something because Split returned in unexpected number of fields.
        }
    }
}

读取CSV的代码相当简单。您可能希望查看其他可以为您处理大量解析详细信息的CSV解析器。那里有一堆。

答案 2 :(得分:0)

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
    {
      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(string));
      csvData.Columns.Add("HoursProductionAmount", typeof(double));

      using (StreamReader sr = new StreamReader(csv_file_path))
      {
        string line = string.Empty;
        while ((line = sr.ReadLine()) != null)
        {
          string[] strRow = line.Split(',');
          DataRow dr = csvData.NewRow();
          dr["RoyaltyEntityID"] = strRow[0];
          dr["ProductionYear"] = strRow[1];
          dr["ProductionMonth"] = strRow[2];
          dr["ProductionEntityID"] = strRow[3];
          dr["ProductionVolume"] = strRow[4];
          dr["SalePrice"] = strRow[5];
          dr["GrossRoyaltyAmount"] = strRow[6];
          dr["TruckingRate"] = strRow[7];
          dr["TotalNetRoyalty"] = strRow[8];
          dr["ConfidentialWell"] = strRow[9];
          if (strRow[9] == "Y")
          {
            dr["HoursProductionAmount"] = strRow[10];
          }
          else
          {
            dr["HoursProductionAmount"] = "0";
          }

          csvData.Rows.Add(dr);
        }
      }

  return csvData;

} enter code here