我有一个上传Excel文件的MVC文件上传解决方案,我在使用Dimension.End.Row属性将Excel文档行读到文件末尾时出现问题,我想要读取到最后一个填充的行而不是整个电子表格行,因为它使用空引用错误轰炸我的代码,Excel来自外部源,它是一个锁定文件,有大约7000行,但只填充了大约3000行对于数据, Dimension.End.Row 属性读取整个7000行,因此当我循环并映射行和列时,在最后填充的数据行3001之后,它具有空值。我怎样才能启用它来只读取excel文件中填充的行,就像我说的那样我不能将这个文件修改为锁定和只读,我只能读取并上传它。请参阅下面的代码。
[HttpPost]
public ActionResult Upload(FormCollection formCollection)
{
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 suppleirList = new List<CleanSupplierClaim>();
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();
var noOfColumns = workSheet.Dimension.End.Column;
var noOfRows = workSheet.Dimension.End.Row;// Here is where my issue is
for (int rowIterator = 5; rowIterator < noOfRows; rowIterator++)
{
var claim = new CleanSupplierClaim();
claim.Action = workSheet.Cells[rowIterator, 1].ToString();
claim.Line_Number = workSheet.Cells[rowIterator, 2].Value.ToString();
claim.Total_Claim = workSheet.Cells[rowIterator, 3].Value.ToString();
claim.ClaimReference = workSheet.Cells[rowIterator, 4].Value.ToString();
claim.Supplier_Claim = workSheet.Cells[rowIterator, 5].Value.ToString();
claim.Currency = workSheet.Cells[rowIterator, 6].Value.ToString();
suppleirList.Add(claim);
}
}
}
}
return View("Index");
答案 0 :(得分:1)
你可以做这样的事情;
for (int rowIterator = 5; rowIterator < noOfRows; rowIterator++)
{
if(workSheet.Cells[rowIterator, 1] == null)//can this be null?
{
break; //if it's null exit from the for loop
}
var claim = new CleanSupplierClaim();
claim.Action = workSheet.Cells[rowIterator, 1].ToString();
claim.Line_Number = workSheet.Cells[rowIterator, 2].Value.ToString();
claim.Total_Claim = workSheet.Cells[rowIterator, 3].Value.ToString();
claim.ClaimReference = workSheet.Cells[rowIterator, 4].Value.ToString();
claim.Supplier_Claim = workSheet.Cells[rowIterator, 5].Value.ToString();
claim.Currency = workSheet.Cells[rowIterator, 6].Value.ToString();
suppleirList.Add(claim);
}
答案 1 :(得分:0)
您可以尝试以下操作:
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());
}
}
}
}
Reff:http://sforsuresh.in/reading-excel-file-using-epplus-package/