Read Excel using LINQ

后端 未结 3 1774
自闭症患者
自闭症患者 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:41

    Suggestion 1

    Checkout THIS link......as AKofC suggests, creating a class to hold your data would be your first port of call. The link I have posted has a small example of the sort of idea we are proposing.

    Suggestion 2 with example...

    The obvious thing to do from the code you have posted would be to create a new class to store your book information in.

    Then you simply define which fields from your excel document it is that you want to pass into the new instance of your bookinformation class.

    New Book Information Class:

    class MyBookInfo
    {
        public string CountryName { get; set; }
        public string BookCode { get; set; }
        public string BookName { get; set; }
    }
    

    Method To Retrieve Info:

    public void GetMyBookInfoFromExcelDocument()
            {
                string filename = @"C:\\" + "Book1.xls";
                string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                              "Data Source=" + filename + ";" +
                                              "Extended Properties=Excel 8.0;";
    
                OleDbDataAdapter dataAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
                DataSet myDataSet = new DataSet();
                dataAdapter.Fill(myDataSet, "BookInfo");
                DataTable dataTable = myDataSet.Tables["BookInfo"];
    
    
                var rows = from p in dataTable.AsEnumerable()
                           where p[0].ToString() != null || p[0].ToString() != "" && p.Field("F2") != null
                           select new MyBookInfo
                           {
                               CountryName = p.Field("InsertFieldNameHere"),
                               BookCode = p.Field("InsertFieldNameHere"),
                               BookName = p.Field("InsertFieldNameHere")
                           };
            }
    

提交回复
热议问题