简体   繁体   English

给定列名的字符串数组,如何将.csv文件读取到DataTable?

[英]Given string array of column names, how do I read a .csv file to a DataTable?

Assume I have a .csv file with 70 columns, but only 5 of the columns are what I need. 假设我有一个包含70列的.csv文件,但是我只需要其中5列。 I want to be able to pass a method a string array of the columns names that I want, and for it to return a datatable. 我希望能够向方法传递我想要的列名称的字符串数组,并使其返回数据表。

private void method(object sender, EventArgs e) {
    string[] columns =
    {
        @"Column21",
        @"Column48"
    };
    DataTable myDataTable = Get_DT(columns);
}

public DataTable Get_DT(string[] columns) {
    DataTable ret = new DataTable();
    if (columns.Length > 0) 
    {
        foreach (string column in columns)
        {
              ret.Columns.Add(column);
        }

        string[] csvlines = File.ReadAllLines(@"path to csv file");
        csvlines = csvlines.Skip(1).ToArray();  //ignore the columns in the first line of the csv file

        //this is where i need help... i want to use linq to read the fields
        //of the each row with only the columns name given in the string[] 
        //named columns
    }
    return ret;
}

You can look at https://joshclose.github.io/CsvHelper/ 您可以查看https://joshclose.github.io/CsvHelper/

Think Reading individual fields is what you are looking for 认为阅读单个字段是您所需要的

var csv = new CsvReader( textReader );
while( csv.Read() )
{
    var intField = csv.GetField<int>( 0 );
    var stringField = csv.GetField<string>( 1 );
    var boolField = csv.GetField<bool>( "HeaderName" );
}

We can easily do this without writing much code. 我们无需编写太多代码就可以轻松地做到这一点。

Exceldatareader is an awesome dll for that, it will directly as a datable from the excel sheet with just one method. Exceldatareader是一个很棒的dll,它将仅通过一种方法直接作为Excel工作表中的datable。

here is the links for example: http://www.c-sharpcorner.com/blogs/using-iexceldatareader1 例如,以下是链接: http : //www.c-sharpcorner.com/blogs/using-iexceldatareader1

http://exceldatareader.codeplex.com/ http://exceldatareader.codeplex.com/

Hope it was useful kindly let me know your thoughts or feedbacks 希望它有用,让我知道您的想法或反馈

Thanks 谢谢

Karthik KARTHIK

var data = File.ReadAllLines(@"path to csv file");
// the expenses row
var query = data.Single(d => d[0] == "Expenses");
//third column
int column21 = 3;
return query[column21];

Read the first line of the file, line.Split(',') (or whatever your delimiter is), then get the index of each column name and store that. 读取文件的第一行line.Split(',') (或任何分隔符),然后获取每个列名称的索引并将其存储。 Then for each other line, again do a var values = line.Split(',') , then get the values from the columns. 然后,对于其他每一行,再次执行var values = line.Split(',') ,然后从列中获取值。

Quick and dirty version: 快速而肮脏的版本:

string[] csvlines = File.ReadAllLines(@"path to csv file");
//select the indices of the columns we want
var cols = csvlines[0].Split(',').Select((val,i) => new { val, i }).Where(x => columns.Any(c => c == x.val)).Select(x => x.i).ToList();
//now go through the remaining lines
foreach (var line in csvlines.Skip(1))
{
    var line_values = line.Split(',').ToList();
    var dt_values = line_values.Where(x => cols.Contains(line_values.IndexOf(x)));
    //now do something with the values you got for this row, add them to your datatable
}

As others have stated a library like CsvReader can be used for this. 正如其他人所说的那样,可以使用CsvReader之类的库。 As for linq, I don't think its suitable for this kind of job. 至于linq,我认为它不适合这种工作。

I haven't tested this but it should get you through 我还没有测试过,但是应该可以帮助您

using (TextReader textReader = new StreamReader(filePath))
{
    using (var csvReader = new CsvReader(textReader))
    {
        var headers = csvReader.FieldHeaders;
        for (int rowIndex = 0; csvReader.Read(); rowIndex++)
        {
            var dataRow = dataTable.NewRow();
            for (int chosenColumnIndex = 0; chosenColumnIndex < columns.Count(); chosenColumnIndex++)
            {
                for (int headerIndex = 0; headerIndex < headers.Length; headerIndex++)
                {
                    if (headers[headerIndex] == columns[chosenColumnIndex])
                    {
                        dataRow[chosenColumnIndex] = csvReader.GetField<string>(headerIndex);
                    }
                }
            }
            dataTable.Rows.InsertAt(dataRow, rowIndex);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM