从Excel中读取两列到Dictionary <ID,string>?

我必须从Excel(ID和值)读取两列到使用C#的字典。 你能告诉我如何实现这个任务吗?

假设你有一个名为“国家”的工作表,其代码和名称在前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(); } } 

我build议使用外部免费库EPPLUS: http ://epplus.codeplex.com/这是非常快速和可靠的东西(办公自动化或使用oledb是不是)。 只需在via epplus中阅读,使用ToDataTable()方法并将数据表读入字典。