简体   繁体   English

从Excel书籍到字典阅读两列 <ID,string> ?

[英]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#. 我必须使用C#从Excel(ID和值)到Dictionary读取两列。 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). 我建议使用外部免费库EPPLUS: http ://epplus.codeplex.com/这是非常快速和可靠的(某些办公自动化或使用oledb并非如此)。 Simply read in the via epplus, use the ToDataTable() method and read the datatable into your dictionary. 只需通过epplus读取,使用ToDataTable()方法并将数据表读取到字典中即可。

assuming you have a sheet named "Country" with code and name in the first 2 columns and also excel 2010. 假设您有一个名为“国家/地区”的工作表,其代码和名称位于前2列中,并且也是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();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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