Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert xls and xlsx to Datatable in C#

Tags:

c#-4.0

I am working in converting ths xls and xlsx to datatable in c#. I have used this code.

public DataTable ReadDataExcel(string filepath)
    {
        FileStream stream = File.Open(filepath, FileMode.Open, FileAccess.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
        excelReader.IsFirstRowAsColumnNames = true;
        DataSet result = excelReader.AsDataSet();
        DataTable dt = new DataTable();
        dt = result.Tables[0];
        return dt;
    }

In case of xls, its working fine. Whenever i used xlsx its not working. Its giving 'Object Reference' error.

Whether there are any other way to convert both the xls and xlsx to datatable. I am not interested in using 'Microsoft.Jet.OLEDB'....

like image 203
RobinHood Avatar asked Nov 01 '22 17:11

RobinHood


1 Answers

This is the answer.

For importing xlsx,

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

For importing xls,

IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
like image 80
RobinHood Avatar answered Jan 04 '23 15:01

RobinHood