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

时间:2015-05-25 05:54:16

标签: 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();
    }

查看

@ViewBag.excelRead

如何从所有行中获取值?急需这个帮助!感谢。

2 个答案:

答案 0 :(得分:4)

试试这个(扩展@Sachu&#39对该问题的评论) -

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();
}

答案 1 :(得分:1)

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

希望这有帮助