Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import CSV file with white-space in header with ServiceStack.Text

I am using ServiceStack.Text library for reading from CSV files in C#.

I would like to know how to deserialize CSV to objects where CSV contains white space separated header ?

I am using this code to deserialize CSV to empClass object:

  List<empClass> objList = File.ReadAllText(filePath).FromCsv<List<empClass>>();

If I have a csv file like this

EmpId,Employee Name,Employee Address 
12,JohnSmith,123 ABC Street

and my class is like

public class empClass{
public string EmpId;
public string Employee_Name;
public string Employee_Address;
}

It populates EmpId but it doesn't populate Employee Name and Employee Address as it contains the white-space in the header.

Will be grateful if anyone can help.

like image 865
Sugat Avatar asked Dec 06 '16 06:12

Sugat


People also ask

Can CSV have space?

You can put quotes, dashes and spaces in the CSV file. Fields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes.

Can a CSV file have formatting?

Data saved in CSV will not retain data formatting.

Can CSV have headers?

CSV and spreadsheet content rules. Each row in the file must contain the same number of cells. This rule also applies to the header row. The first row must contain column headers.


1 Answers

The POCO class needs to match the property names of the CSV which has spaces in it, replacing it with an underscore doesn't make it match, you should also use public properties when using ServiceStack's serializers.

Since properties can't have spaces you can try using an alias, e.g:

[DataContract]
public class EmpClass
{
    [DataMember]
    public string EmpId { get; set; }
    [DataMember(Name="Employee Name")]
    public string EmployeeName  { get; set; }
    [DataMember(Name="Employee Address")]
    public string EmployeeAddress  { get; set; }
}
like image 126
mythz Avatar answered Oct 02 '22 08:10

mythz