Get all the values from excel file by using linqtoexcel

懵懂的女人 提交于 2019-12-08 05:27:21

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/30432006/get-all-the-values-from-excel-file-by-using-linqtoexcel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!