简体   繁体   English

EPPlus excel读取IndexOutOfRangeException

[英]EPPlus excel read IndexOutOfRangeException

I want to read data from excel (.xlsx or .xls) file I am using EPPlus but it give that error IndexOutOfRangeException: Worksheet position out of range. 我想从我正在使用EPPlus的excel(.xlsx或.xls)文件中读取数据,但它给出了该错误IndexOutOfRangeException:工作表位置超出范围。 in this line 在这条线

  OfficeOpenXml.ExcelWorksheet workSheet = package.Workbook.Worksheets[0];

here is my all code.Here is my excel file for redad( http://yazilimsozluk.com/a.xlsx ) .Are there any solution for excel read which works with .xlsx and .xls excel file? 这是我所有的代码。这是我的redad的excel文件( http://yazilimsozluk.com/a.xlsx )。是否有适用于.xlsx和.xls excel文件的excel读取解决方案?

if (Request != null) {
  HttpPostedFileBase file = Request.Files["UploadedFile"];
  if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) {
    string fileName = file.FileName;
    string fileContentType = file.ContentType;
    byte[] fileBytes = new byte[file.ContentLength];
    var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));


    var existingFile = new System.IO.FileInfo(fileName);
    var package = new OfficeOpenXml.ExcelPackage(existingFile);

    OfficeOpenXml.ExcelWorksheet workSheet = package.Workbook.Worksheets[0];

    for (int i = workSheet.Dimension.Start.Column; i <= workSheet.Dimension.End.Column; i++) {
      for (int j = workSheet.Dimension.Start.Row; j <= workSheet.Dimension.End.Row; j++) {
        object cellValue = workSheet.Cells[i, j].Value;
      }
    }
  }
}

First of all EPPlus can not handle .xls files. 首先,EPPlus无法处理.xls文件。 See this answer: 看到这个答案:

Error when trying to read an .xls file using EPPlus 尝试使用EPPlus读取.xls文件时出错

Sample code for reading a file: 读取文件的示例代码:

var package = new ExcelPackage(new FileInfo("sample.xlsx"));

ExcelWorksheet workSheet = package.Workbook.Worksheets.FirstOrDefault();

for (int i = workSheet.Dimension.Start.Column;
        i <= workSheet.Dimension.End.Column;
        i++)
{
    for (int j = workSheet.Dimension.Start.Row;
            j <= workSheet.Dimension.End.Row;
            j++)
    {
        object cellValue = workSheet.Cells[i, j].Value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM