In this article you will learn to read Excel File Data to an Object.
I have a xls file named Employee.xls that contains three columns "Name","Address","Mobile".
Download File: Employee.xls
I have a Employee Object.
Install-Package ExcelDataReader
Download the Project File ImportXlsDataToObject.cs
I have a xls file named Employee.xls that contains three columns "Name","Address","Mobile".
Download File: Employee.xls
I have a Employee Object.
public class Employee
{
public string Name { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
public List<Employee> empList { get; set; }
}
I need the Data from Excel file to my Employee Object.
First Add ExcelDataReader from Nuget in your Project Solution.
Install-Package ExcelDataReader
It'll add some dlls in your Project.
To Read data from xls, the Code is below:
public static void importDataFromXls()
{
Employee data = new Employee();
data.empList = new List<Employee>();
//Reading
from a OpenXml Excel file (2007 format; *.xlsx)
FileStream stream = new FileStream("C:\\Users\\surajm\\Documents\\Employee.xlsx", FileMode.Open);
IExcelDataReader excelReader2007 = ExcelReaderFactory.CreateOpenXmlReader(stream);
//DataSet
- The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader2007.AsDataSet();
//Data
Reader methods
foreach (DataTable table in result.Tables)
{
for (int i = 1; i < table.Rows.Count; i++)
{
//for (int j = 0; j < table.Columns.Count; j++)
Employee emp = new Employee();
emp.Name =
table.Rows[i].ItemArray[0].ToString();
emp.Address =
table.Rows[i].ItemArray[1].ToString();
emp.Mobile =
table.Rows[i].ItemArray[2].ToString();
data.empList.Add(emp);
}
}
//Free
resources (IExcelDataReader is IDisposable)
//excelReader2003.Close();
excelReader2007.Close();
}
Download the Project File ImportXlsDataToObject.cs
0 comments:
Post a Comment