读取Excel

 /// <summary>
        /// 支持的格式有 xls、xlsx
        /// </summary>
        /// <param name="uploadPath"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public DataTable GetExcelTableInfo(string uploadPath, string sheetName)
        {
            string filetype = System.IO.Path.GetExtension(uploadPath);//获取文件扩展名
            string Xls_ConnStr = "";
            if (filetype == ".xlsx")
            {
                Xls_ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;Data Source=" + uploadPath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
            }
            else if (filetype == ".xls")
            {
                Xls_ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" + uploadPath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";//HDR为yes 则第一数据行为列名,为no 则自动为列加列名F1  F2  F3
            }
            DataTable myTable = new DataTable();
            //string Xls_ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" + uploadPath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";//HDR为yes 则第一数据行为列名,为no 则自动为列加列名F1  F2  F3
            using (OleDbConnection Conn = new OleDbConnection(Xls_ConnStr))
            {
                try
                {
                    Conn.Open();
                    string sql_str = "select * from [{0}$]";
                    sql_str = string.Format(sql_str, sheetName);
                    OleDbDataAdapter da = new OleDbDataAdapter(sql_str, Conn);
                    da.Fill(myTable);
                    Conn.Close();
                }
                catch (Exception ex)
                {
                    writeLog(ex.Message, "");
                    myTable = null;
                }
            }
            return myTable;
        }

  

posted @ 2014-04-17 17:28  只不过一场戏  阅读(84)  评论(0编辑  收藏  举报