.net 查詢Excel

public static DataTable GetCSVDataTable(string FileName)
        {
            System.Data.OleDb.OleDbConnection cn = null;
            DataTable dt = new DataTable();
            string strSheet = "";
            try
            {
                string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileLocation + ";Extended Properties='Text;HDR=yes'";
                //查詢語句 
                cn = new System.Data.OleDb.OleDbConnection(strConn);
                cn.Open();
                Object[] objs = new Object[] { null, null, null, "TABLE" };
                dt = cn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, objs);

                if (dt.Rows.Count > 0)
                {
                    strSheet = dt.Rows[0]["TABLE_NAME"].ToString();
                }
                dt = new DataTable();
                string strSql = "SELECT  *  FROM [" + FileName + "] ";
                System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(strSql, strConn);
                da.Fill(dt);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                if ((cn != null))
                {
                    cn.Close();
                }
                if ((System.IO.File.Exists(FileLocation + FileName)))
                {
                    System.IO.File.Delete(FileLocation + FileName);
                }
            }
            return dt;
        }

 

posted @ 2012-05-02 10:07  秋日私语的博客  阅读(1121)  评论(0编辑  收藏  举报