asp.net - 如何将流excel文件转换为数据表C#?

标签 asp.net excel xlsx epplus

我使用 Epplus 从流中读取 xlsx 文件。

它有一个错误,它无法读取我的工作簿中的某些列。如何在没有 epplus 的情况下将 xlsx 文件从流读取到数据表?

我的旧代码:

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

我没有报告它,但我尝试了很多组合。如果工作表中有空列,epplus reader 无法正确读取列值。

最佳答案

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



你能描述一下这个bug吗,你有吗reported它还是已经知道,您使用的是什么版本?

这是将 excel 文件加载到 DataTable 的简单方法。与 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;
    }
}

关于asp.net - 如何将流excel文件转换为数据表C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11239805/

相关文章:

c# - VSTO 加载项 : Reference in the manifest does not match the identity of the downloaded assembly

javascript - xlsx - 写入已知单元格编号。无法赋值

r - 使用R包xlsx,读取Excel文件时是否可以设置na.strings?

c# - 如何在Web应用程序中实现TCP/IP响应器 "service"

ASP.net MVC 4 Web Api 路由,其中​​包含文件名

excel - 嵌套的 IF 语句返回 false

java - 如何使用java合并XLS中超过255个单元格

c# - ASP.NET:如何允许用户对 gridview 列进行重新排序?

asp.net - 如何使我的 Modal Popup Extender 成为模态? (禁用背景)

c# - C#/.Net 的 Excel XLSTART 问题