Read Excel using LINQ

后端 未结 3 1748
自闭症患者
自闭症患者 2020-12-28 17:48

I want to read excel 2003( cannot change as its coming from third party) and group data in List or Dictionary (I don\'t which one is good) for example belo

3条回答
  •  醉梦人生
    2020-12-28 18:26

    There's two things you need to do:

    First, you need to reformat the spreadsheet to have the column headers on the first row like the table below shows

    | Country | Code | Name    | IBN  |
    |---------|------|---------|------|
    | Aust    | UX   | test1   | 34   |
    | Aust    | UZ   | test2   | 345  |
    | Aust    | UN   | test3   | 5654 |
    | US      | UX   | name1   | 567  |
    | US      | TG   | name2   | 123  |
    | US      | UM   | name3   | 234  |
    

    Second, use the Linq to Excel library to retrieve the data. It takes care of making the oledb connection and creating the sql for you. Below is an example of how easy it is to use the library

    var book = new ExcelQueryFactory("pathToExcelFile");
    var australia = from x in book.Worksheet()
                    where x["Country"] == "Aust"
                    select new
                    {
                       Country = x["Country"],
                       BookCode = x["Code"],
                       BookName = x["Name"]
                    };
    

    Checkout the Linq to Excel intro video for more information about the open source project.

提交回复
热议问题