Get all the values from excel file by using linqtoexcel

Shihan Khan picture Shihan Khan · May 25, 2015 · Viewed 12.2k times · Source

I'm using linqtoexcel in my asp.net mvc 4 project to read an excel file & get all the values from there. But I'm only getting the values of last row. Here are my codes,

Controller

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

View

@ViewBag.excelRead

How can I get the values from all the rows? Need this help badly! Thanks.

Answer

Siva Senthil picture Siva Senthil · May 25, 2015

Try this (expanding on @Sachu's comment to the question) -

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