简体   繁体   English

使用OLEDB从Excel读取数据

[英]Read Data from Excel using OLEDB

I read an excel file using OLEDB. 我使用OLEDB读取了一个Excel文件。 Below is the code: 下面是代码:

            string conn;             
            conn = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
            ("Data Source=" + _filename + ";" +
            "Extended Properties=\"Excel 12.0;\""));
            OleDbConnection oleDBCon = new OleDbConnection(conn);
            oleDBCon.Open();
            DataTable dt = oleDBCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);                    
            string SSQL = "SELECT * from [ Sheet1$ ]";
            OleDbDataAdapter oleDA = new OleDbDataAdapter(SSQL, conn);
            DataSet ds = new DataSet();
            oleDA.Fill(ds);
            DataTable _DtTable = ds.Tables[0];
            oleDBCon.Close();
            dataGridView1.DataSource = _DtTable;
            foreach (DataRow rows in _DtTable.Rows)
            {
                string Description = rows[0].ToString();
                string Code= rows[1].ToString();              
                textBox1.AppendText("Printing Description: " + Description + " and Code: " + Code + ",Date:" + DateTime.Now.ToString() + Environment.NewLine);                             
            }

The excel file is as follows: excel文件如下:

在此处输入图片说明

The data printed in textBox1 are: 在textBox1中打印的数据是:

Printing Description:Desc 2 and Code: Code 2,Date:20/12/2014 12:36:54 μμ
Printing Description: Desc 3 and Code: Code 3,Date:20/12/2014 12:36:54 μμ

So, my problem is that the 1st row of excel is going to the header of the Datatable. 因此,我的问题是excel的第一行将转到Datatable的标题。 How can I avoid that (without adding any extra 1st row to excel)? 如何避免这种情况(不向Excel添加任何额外的第一行)?

Just add "HDR=No" at the end of your connection string which means "No header row that indicates column but it contains data", then you will be able to fetch 1st row data also. 只需在连接字符串的末尾添加“ HDR = No”,这意味着“没有指示列的标题行,但其中包含数据”,那么您也可以获取第一行数据。

So your complete connection string would be 所以您的完整连接字符串将是

 conn = ("Provider=Microsoft.ACE.OLEDB.12.0;" +
        ("Data Source=" + _filename + ";" +
        "Extended Properties=\"Excel 12.0;\";HDR=No"));

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

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