C#使用ado.net读取excel文件

 

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + fileName + ";Extended Properties=Excel 8.0;"; ;
                OleDbConnection Conn = new OleDbConnection(strConn);
                Conn.Open();
                //获取Sheet的名字。
                DataTable schemaTable = Conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
                //schemaTable.Rows.Count值为Sheet的总数

                List<string> tableNames = new List<string>();

                //注意schemaTable是从0开始,即第0个是第1个Sheet。第2列是Sheet名。
                for (int i = 0; i < schemaTable.Rows.Count; i++)
                {
                    string s = schemaTable.Rows[i][2].ToString().Trim();
                    tableNames.Add(s);

                }
                Conn.Close();

                Conn = new OleDbConnection(strConn);
                foreach (string tableName in tableNames)
                {
                    string query = string.Format("SELECT   *   FROM  [{0}]", tableName);

                    OleDbCommand oleCommand = new OleDbCommand(query, Conn);
                    OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
                    DataSet myDataSet = new DataSet();

                    //   将   Excel   的[Sheet1]表内容填充到   DataSet   对象 
                    oleAdapter.Fill(myDataSet, tableName);
                    foreach (DataRow row in myDataSet.Tables[0].Rows)
                    {
                        for (int i = 0; i < myDataSet.Tables[0].Columns.Count; i++)
                        {
                            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\d{11}");
                            string content = row[i].ToString();
                            MatchCollection matches = regex.Matches(content);
                            foreach (Match item in matches)
                            {
                                this.textBox2.Text = this.textBox2.Text + item.Value + Environment.NewLine;
                            }
                        }
                    }
                }
                Conn.Close();

 

你可能感兴趣的:(C++,c,.net,Excel,C#)