Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How convert stream excel file to datatable C#?

I use Epplus to reading xlsx files from stream.

It has a bug , it cant read some columns in my workbook.How can read xlsx files from stream to datatable without epplus ?

my older code:

 public static DataSet ReadExcelFile(Stream stream)
    {
        try
        {
            //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
            IExcelDataReader excelReader =    
                             ExcelReaderFactory.CreateOpenXmlReader(stream);
            //...
            DataSet result = excelReader.AsDataSet();

            return result;

        }
        catch (Exception x)
        {
            throw x;
        }
    }

I didnt report it, but i tried so much combinations.If there are empty columns in worksheet ,epplus reader cant read correctly column values.

like image 299
Mennan Avatar asked Jun 28 '12 07:06

Mennan


1 Answers

"It has a bug , it cant read some columns in my workbook"

Can you describe the bug, have you reported it or is it already known, what version are you using?

Here's a simple approach to load an excel file into a DataTable with EPPlus.

public static DataTable getDataTableFromExcel(string path)
{
    using (var pck = new OfficeOpenXml.ExcelPackage())
    {
        using (var stream = File.OpenRead(path))
        {
            pck.Load(stream);
        }
        var ws = pck.Workbook.Worksheets.First();  
        DataTable tbl = new DataTable();
        bool hasHeader = true; // adjust it accordingly( i've mentioned that this is a simple approach)
        foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
        {
            tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
        }
        var startRow = hasHeader ? 2 : 1;
        for (var rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
        {
            var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
            var row = tbl.NewRow();
            foreach (var cell in wsRow)
            {
                row[cell.Start.Column - 1] = cell.Text;
            }
            tbl.Rows.Add(row);
        }
        return tbl;
    }
}
like image 75
Tim Schmelter Avatar answered Oct 26 '22 00:10

Tim Schmelter