使用linqtoexcel从excel文件中获取所有值
本文关键字:获取 文件 linqtoexcel excel 使用 | 更新日期: 2023-09-27 17:50:41
我在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();
}
<<p> 视图/strong> @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)
{
.....
}
希望能有所帮助