Reputation: 1871
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. 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?
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;
}
}
}
}
Upvotes: 1
Views: 4565
Reputation: 70116
First of all EPPlus can not handle .xls files. See this answer:
Error when trying to read an .xls file using EPPlus
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;
}
}
Upvotes: 2