提取CSV标头数据类型

时间:2016-06-04 12:11:25

标签: c# csv

在我当前的项目中,我试图派生CSV文件的数据类型。例如,以下是.CSV文件。

sepallength,sepalwidth,petallength,petalwidth,class
6.2,2.8,4.8,1.8,Iris-virginica
6.3,2.9,5.6,1.8,Iris-virginica
5.1,3.5,1.4,0.3,Iris-setosa
5.2,3.5,1.5,0.2,Iris-setosa
5.9,3,4.2,1.5,Iris-versicolor
5.7,3,4.2,1.2,Iris-versicolor
5.5,2.6,4.4,1.2,Iris-versicolor
6.4,2.8,5.6,2.2,Iris-virginica

我的要求是程序应该给我以下输出。

  • “sepallength”属于“float”数据类型
  • “sepalwidth”属于“float”数据类型
  • “petallength”属于“float”数据类型
  • “petalwidth”属于“float”数据类型
  • “class”属于“String”数据类型

我写了以下程序。但是,“columnName.GetType()”函数始终返回字符串数据类型。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Microsoft.VisualBasic.FileIO;
using System.IO;

namespace ReadCSVFile
{
    class Program
    {
        static void Main(string[] args)
        {
            // This is a file Path that a user has to input.
            string csv_file_path = @"C:\TestCSV\iris.csv";
            string columnName;

            DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);

            Console.WriteLine("Column Value of the CSV file are as follows:");
            Console.WriteLine("=========================================");

            // This will retrieve columnNames from the table.
            foreach (DataColumn column in csvData.Columns)
            {
                columnName = column.ColumnName;
                Console.WriteLine(columnName);
                Console.WriteLine("Column type " + columnName.GetType());
            }
    }

    /*
     *  This function takes the file Path as an input and returns a Datatable.
    */

    private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
    {
        DataTable csvData = new DataTable();

        try
        {
            // Connect to the .CSV file Path
            using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;

                // This will read the column name of a .CSV file.
                string[] colFields = csvReader.ReadFields();

                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }

                // This code retrieves rows from the .CSV file.
                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;
    }

1 个答案:

答案 0 :(得分:0)

检查我的示例代码: (你不能将它与.columnname一起使用,因为它始终是一个字符串,只有列的内容是不同类型的:

public static void Main()
{
    string str = "6,2"; // float with decimals from europe
    Console.WriteLine(mytesttype(str).GetType());
    str = "6232";
    Console.WriteLine(mytesttype(str).GetType());
    str = "6String";
    Console.WriteLine(mytesttype(str).GetType());
}

static object mytesttype(string str) {

    int i;
    float f;
    if (int.TryParse(str,out i)) return i;
    if (float.TryParse(str, out f)) return f;
    return str;

}