csharp_read_execl

blog:http://www.cnblogs.com/solq

    string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:/test.xlsx;Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\";";

        string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/test.xls;" +  "Extended Properties='Excel 8.0'";

        private void readExecl()

        {



            OleDbConnection con = new OleDbConnection(Connection);



            #region 

            

            /*

                获取多少个表。。。。。

             */

            con.Open();           

            DataTable sheetsName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });



            Console.WriteLine(sheetsName.Rows.Count);

            Console.WriteLine(sheetsName.Rows[0][2].ToString()); // get table name



            #endregion

            /*

            //读取方式一      

            OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", con);



            DataTable dt = new DataTable();

            myCommand.Fill(dt);



            DataSet set = new DataSet();

            myCommand.Fill(set);

           

            foreach (DataRow r in dt.Rows)

            {

               

                String str = r[0].ToString();

                //Console.WriteLine(str);

            }*/



            /*

                如果只想读取前两列可以用:select * from [Sheet1$A:B]

                如果只想读取A1到B2的内容,就用:select * from [Sheet1$A1:B2]

             */

            //读取方式二

            string sql = string.Format("SELECT * FROM [{0}$] ", "Sheet1");

            OleDbCommand myOleDbCommand = new OleDbCommand(sql, con);

            OleDbDataReader myDataReader = myOleDbCommand.ExecuteReader();

            //myDataReader.Read();

            //myDataReader.Read();

            while (myDataReader.Read())

            {

                for(int i=0; i< myDataReader.FieldCount;i++)

                {

                    string c=Convert.ToString(myDataReader.GetValue(i));

                    Console.Write(c+"\t");

                }

                Console.WriteLine("");              

            }

            myDataReader.Dispose();

            con.Close();

        }

 

http://files.cnblogs.com/solq/csharp_read_execl.rar

最终版吧。。。

http://files.cnblogs.com/solq/read_execl.rar

你可能感兴趣的:(exec)