使用linqtoexcel获取excel文件中的所有值

我在我的asp.net mvc 4项目中使用linqtoexcel来读取一个excel文件,并从那里获取所有的值。 但是我只得到最后一行的值。 这是我的代码,

调节器

  public ActionResult ExcelRead() { string pathToExcelFile = "" + @"C:\MyFolder\ProjectFolder\sample.xlsx"; string sheetName = "Sheet1"; var excelFile = new ExcelQueryFactory(pathToExcelFile); var getData = from a in excelFile.Worksheet(sheetName) select a; foreach (var a in getData) { string getInfo = "Name: "+ a["Name"] +"; Amount: "+ a["Amount"] +">> "; ViewBag.excelRead = getInfo; } return View(); } 

视图

 @ViewBag.excelRead 

我怎样才能得到所有行的值? 急需这个帮助! 谢谢。

试试这个(扩展@ Sachu对这个问题的评论) –

 public ActionResult ExcelRead() { string pathToExcelFile = "" + @"C:\MyFolder\ProjectFolder\sample.xlsx"; string sheetName = "Sheet1"; var excelFile = new ExcelQueryFactory(pathToExcelFile); var getData = from a in excelFile.Worksheet(sheetName) select a; string getInfo = String.Empty; foreach (var a in getData) { getInfo += "Name: "+ a["Name"] +"; Amount: "+ a["Amount"] +">> "; } ViewBag.excelRead = getInfo; return View(); } 

将getDate设置为.ToList()

 var getData = (from a in excelFile.Worksheet(sheetName) select a); List<string> getInfo = new List<string>(); foreach (var a in getData) { getInfo.Add("Name: "+ a["Name"] +"; Amount: "+ a["Amount"] +">> "); } ViewBag.excelRead = getInfo; return View(); 

然后将其传递给视图,并使用@ ViewBag.excelRead执行foreach循环

  foreach (var data in @ViewBag.excelRead) { ..... } 

希望这可以帮助