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

Shi*_*han 4 c# asp.net-mvc excel linq-to-excel

linqtoexcel在我的asp.net mvc 4项目中使用它来读取 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();
    }
Run Code Online (Sandbox Code Playgroud)

看法

@ViewBag.excelRead
Run Code Online (Sandbox Code Playgroud)

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

Siv*_*hil 6

试试这个(扩展@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();
}
Run Code Online (Sandbox Code Playgroud)