c#操作excel

最近的一个项目中碰到了,记录一下!所谓好记性不如烂笔头嘛!

 

        /// <summary>
        /// 读取excel
        /// </summary>
        /// <param name="FilePath">EXCEL地址</param>
        /// <param name="sheetName">excel内表名字</param>
        /// <returns></returns>
        public static DataTable GetExcel(string FilePath, string sheetName)
        {
            string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + FilePath + ";Extended Properties=Excel 8.0;";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);

            OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [" + sheetName + "$]", strConn);

            DataTable myDataTable = new DataTable();
            try
            {
                myCommand.Fill(myDataTable);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                throw new Exception();
            }
            finally
            {
                conn.Close();
            }
            return myDataTable;
        }
posted @ 2010-06-08 19:13  qianlifeng  阅读(1091)  评论(0编辑  收藏  举报