How convert stream excel file to datatable C#?

后端 未结 2 481
忘了有多久
忘了有多久 2020-12-30 08:48

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 eppl

2条回答
  •  星月不相逢
    2020-12-30 09:22

    "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;
        }
    }
    

提交回复
热议问题