C# 使用linqtoexcel从excel文件中获取所有值
我在我的C# 使用linqtoexcel从excel文件中获取所有值,c#,asp.net-mvc,excel,linq-to-excel,C#,Asp.net Mvc,Excel,Linq To Excel,我在我的asp.NETMVC4项目中使用linqtoexcel读取excel文件并从中获取所有值。但我只得到最后一行的值。这是我的密码 控制器 public ActionResult ExcelRead() { string pathToExcelFile = "" + @"C:\MyFolder\ProjectFolder\sample.xlsx"; string sheetName = "Sheet1"; v
asp.NETMVC4
项目中使用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
如何从所有行中获取值?非常需要这个帮助!谢谢。将getDate设置为.ToList() 希望这有帮助试试这个(扩展@Sachu对这个问题的评论)——
在foreach循环中,Viewbag.excelRead正在分配当前行。这就是为什么您只获得视图中的最后一行。您应该将其分配给列表,并调用视图中的列表。谢谢。你能用代码给我举个例子吗?我在asp.net中有点不知所措。我在查看
@model List
编译器错误消息时遇到了编译错误
:CS0246:找不到类型或命名空间名称“getData”(您是否缺少using指令或程序集引用?
让我们来看看。我遇到了System.Collections.Generic.List1[System.String]
asViewBag.excelRead
视图中的值。@Sinoscras,我已经编辑了代码,请检查此代码。我已经删除了这个列表,因为您可能正在绑定到一个HTML div,而不是在结果上循环。为了简洁起见,您也可以这样做。@Sin Oscuras,如果您需要在“Name…”的两行之间换行,那么请在字符串末尾添加。这是一个很好的解决方法。谢谢你的耐心。这很有效!:)工作表名称是什么?
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();
foreach (var data in @ViewBag.excelRead)
{
.....
}
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();
}