簡體   English   中英

從Excel書籍到字典閱讀兩列 <ID,string> ?

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

我必須使用C#從Excel(ID和值)到Dictionary讀取兩列。 您能告訴我如何完成這項任務嗎?

我建議使用外部免費庫EPPLUS: http ://epplus.codeplex.com/這是非常快速和可靠的(某些辦公自動化或使用oledb並非如此)。 只需通過epplus讀取,使用ToDataTable()方法並將數據表讀取到字典中即可。

假設您有一個名為“國家/地區”的工作表,其代碼和名稱位於前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