【问题标题】:Get all the values from excel file by using linqtoexcel使用 linqtoexcel 从 excel 文件中获取所有值
【发布时间】:2015-05-25 21:31:26
【问题描述】:

我在我的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

如何从所有行中获取值?非常需要这个帮助!谢谢。

【问题讨论】:

  • 在 foreach 循环中,Viewbag.excelRead 正在分配当前行..这就是为什么您只能在视图中看到最后一行..您应该将其分配给一个列表并在视图中调用该列表
  • 谢谢。你能通过代码给我一个例子吗?我在 asp.net 中有点菜鸟。

标签: c# asp.net-mvc excel linq-to-excel


【解决方案1】:

试试这个(扩展@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();
}

【讨论】:

  • 我将System.Collections.Generic.List1[System.String] 视为ViewBag.excelRead 值。
  • @SinOscuras,我已经编辑了代码,检查这个。我已经删除了 List ,因为您可能绑定到 HTML div 而不是在结果上循环。为简洁起见,您也可以这样做。
  • @Sin Oscuras,如果您需要在两行“Name...”之间换行,请在字符串末尾添加
  • 非常好的解决方法。非常感谢您的耐心。这很好用! :)
  • 工作表名称是什么?
【解决方案2】:

将 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)
    {
    .....
    }

希望对你有帮助

【讨论】:

  • 我正在查看Compilation error @model List&lt;getData&gt;
  • Compiler Error Message: CS0246: The type or namespace name 'getData' could not be found (are you missing a using directive or an assembly reference?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多