简体   繁体   中英

Read two columns from Excel book to Dictionary<ID,string>?

I have to read two columns from Excel (ID and value) to Dictionary using C#. Can you please advise me how to achieve this task?

I would recommend using the external free library EPPLUS: http://epplus.codeplex.com/ It's very fast and reliable (something which office automation or using oledb is NOT). Simply read in the via epplus, use the ToDataTable() method and read the datatable into your dictionary.

assuming you have a sheet named "Country" with code and name in the first 2 columns and also excel 2010.

    using System.Data.OleDb;

    static void Main()
    {
        string excl_connection_string = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\CountryCode.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES""";

        string sql = "SELECT * FROM [Country$]";

        OleDbConnection con = new OleDbConnection(excl_connection_string);
        OleDbCommand cmd = new OleDbCommand(sql, con);

        try
        {
            con.Open();
            OleDbDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine("Country Code = {0}, Name= {1}", reader.GetString(0), reader.GetString(1));
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            con.Dispose();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM