4

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.

Shihan Khan
  • 2,180
  • 4
  • 34
  • 67
  • here on foreach loop the Viewbag.excelRead is assigning the current row..thats why you are getting only last row in view..you should assign this to a list and call the list in the view – Sachu May 25 '15 at 06:02
  • Thanks. Can you give me an example by code? I'm kinda noob in asp.net. – Shihan Khan May 25 '15 at 06:04

2 Answers2

6

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();
}
Siva Senthil
  • 610
  • 6
  • 22
1

Make the getDate as .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();

Then pass this to the view and do a foreach loop with @ViewBag.excelRead

    foreach (var data in @ViewBag.excelRead)
    {
    .....
    }

Hope this helps

Sachu
  • 7,555
  • 7
  • 55
  • 94
  • I'm getting `Compilation error` in view for `@model List` – Shihan Khan May 25 '15 at 06:19
  • `Compiler Error Message: CS0246: The type or namespace name 'getData' could not be found (are you missing a using directive or an assembly reference?)` – Shihan Khan May 25 '15 at 06:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/78664/discussion-between-sachu-and-sin-oscuras). – Sachu May 25 '15 at 07:19