簡體   English   中英

C#並從Excel文件中讀取值

[英]C# and read values from an Excel file

我有一個Excel文件,各列都有名稱(數據源不受我控制..它由客戶端提供給我)。 盡管列會更改,但列標題永遠不會更改。

在文件中,它稱為“名字”

如何訪問同一列中每個單元格中的數據?

打開您的Excel文件作為數據庫。 這樣,您就不必擔心列的位置了:

string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\MyExcelFile.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";
using (var conn = new System.Data.OleDb.OleDbConnection(connString)) {
    conn.Open();
    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("Select * From [SheetName$]", conn);
    OleDbDataReader reader = cmd.ExecuteReader();
    int firstNameOrdinal = reader.GetOrdinal("First Name");
    int lastNameOrdinal = reader.GetOrdinal("Last Name");
    while (reader.Read()) {
        Console.WriteLine("First Name: {0}, Last Name: {1}", 
            reader.GetString(firstNameOrdinal), 
            reader.GetString(lastNameOrdinal));
    }
}

您可以在使用ODBC連接到文件並下載工作表內容的地方執行類似的操作。

 private bool DownloadExcelData(string fileName, ref DataTable informationDT)
            {
                // bool success
                bool success = true;

                // open the file via odbc
                string connection = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
                connection = String.Format(connection, FilePath + fileName);
                OleDbConnection conn = new OleDbConnection(connection);
                conn.Open();

                try
                {
                    // retrieve the records from the first page
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Information$]", conn);
                    OleDbDataAdapter adpt = new OleDbDataAdapter(cmd);
                    adpt.Fill(informationDT);
                }
                catch { success = false; }

                // close the connection
                conn.Close();
                return success;
            }

以下是一些xls和xlsx文件的示例ODBC連接:

<add name="xls" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;'" />
    <add name="xlsx" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0" />

我過去已經成功使用FileHelpers庫讀取Excel文件。

我過去使用過excelLibrary ,發現它非常易於使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM