user13255166
user13255166

Reputation: 11

C# CSV File : How to skip few columns while reading csv file using datatable

There are some conditional columns which i need to skip while reading csv using datatable. For example: My csv file has headers like Emp_Id, Emp_Name,Dept , Role , Addree and Salary. I want to skip Emp_Name and Role column while reading csv file and import the rest.

Emp_id Emp_Name Dept Role Address Salary

I am using below code to read csv file without any column skip But now i want to skip some columns: List listOfCol = new List(); DataTable dt = new DataTable();

        for (int i = 1; i <= colCount; i++)
        {
            string colName = XlRange.Cells[1, i].Value2.ToString();
            DataColumn dataColumn = new DataColumn(colName);
            dt.Columns.Add(dataColumn);
            listOfCol.Add(colName);
        }

        for (int i = 2; i <= rowCount; i++)
        {
            DataRow dataRow = dt.NewRow();

            for (int j = 1; j <= colCount; j++)
            {
                if (XlRange.Cells[i, j] != null && XlRange.Cells[i, j].Value2 != null)
                {
                    dataRow[listOfCol[j - 1].ToString()] = XlRange.Cells[i, j].Value2.ToString();
                }
                else
                {
                    dataRow[listOfCol[j - 1].ToString()] = "";
                }
            }
            dt.Rows.Add(dataRow);
        }

Upvotes: 1

Views: 1270

Answers (2)

cluebit
cluebit

Reputation: 31

It depends on how you are already building DataTable.

You may try NuGet package csvHelper

And a class definition that looks like this.

public class Foo {
    public int Id { get; set; }
    public string Name { get; set; }
}

If our class property names match our CSV file header names, we can read the file without any configuration.

using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) {
    var records = csv.GetRecords<Foo>();
}

To select only specific columns use column index

public class Foo { 
    [Index(0)]
    public int Id { get; set; }

    [Index(1)]
    public string Name { get; set; }
 }

Thanks

Upvotes: 3

Mandivamba
Mandivamba

Reputation: 105

Can you put the sample code you are working with so we can assist better. The crude way to do it would be as your read each line of the csv file spilt it by the delimiter which returns an array of your items and you cherry pick by index to add to you datatable.

Upvotes: 0

Related Questions