如何使用EPPlus阅读Excel [英] How to read excel using EPPlus

查看:65
本文介绍了如何使用EPPlus阅读Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用.net 4.5

using .net 4.5

我正在尝试使用EPPlus(v4.0.4)读取.xls / .xlsx文件,但出现错误。因此,对于相同的错误有疑问,但没有一个问题与我的问题相关。

I'm trying to read .xls/.xlsx file using EPPlus (v4.0.4), but get an error. SO has questions on the same error but none relate or solve my problem.

protected void Page_Load(object sender, EventArgs e)
    {
        GetDataTableFromExcel(@"D:\test.xlsx");
    }

private DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
  using (var pck = new OfficeOpenXml.ExcelPackage())
   {
     using (var stream = File.OpenRead(path))
      {
        pck.Load(stream);
      }
     var ws = pck.Workbook.Worksheets[1];
     DataTable tbl = new DataTable();
     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 (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
     {
       var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
       DataRow row = tbl.Rows.Add();
       foreach (var cell in wsRow)
        {
          row[cell.Start.Column - 1] = cell.Text;
        }
     }
   return tbl;
  }
}

错误发生在 pck .Load(stream);


在写操作期间发生磁盘错误。 (来自
HRESULT的异常:0x8003001D(STG_E_WRITEFAULT)

A disk error occurred during a write operation. (Exception from HRESULT: 0x8003001D (STG_E_WRITEFAULT)


推荐答案

一个简单的示例您可以使用EPPlus读取excel文件:

A simple example how you can use EPPlus to read excel file:

Reff: http://sforsuresh.in/reading-excel-file-using-epplus-package/

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value.ToString().Trim());
            }
        }
    }
}

这篇关于如何使用EPPlus阅读Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆