使用OLEDB读取excel和csv文件

时间:2023-02-10 07:25:03

这是我第一次在博客上写东西,简单的为大家分享一个oledb读取文件的功能吧,这两天在做一个文件导入数据库的小demo,就想着导入前先在页面上展示一下,之前调用Microsoft.Office.Interop.*.dll的组件,代码看起来很是冗余,于是乎选择了这种方式,添加引用 using System.Data.OleDb;代码分享给大家,有什么不足或补充,希望大家多多发言,共同进步哈!

  /// <summary>
        /// 使用OLEDB读取excel和csv文件
        /// </summary>
        /// <param name="path">文件所在目录地址</param>
        /// <param name="name">文件名</param>
        /// <returns></returns>
        public static DataSet ReadFile(string path, string name)
        {
            if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(name) || !File.Exists(path+name))
                return null;
            // 读取excel 
            string connstring = string.Empty;
            string strSql = string.Empty;
            if (name.EndsWith(".xls") || name.EndsWith(".xlsx"))
            {
                connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + name + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
                strSql = "select * from [sheet1$]";
            }
            // 读取csv文件
            else if (name.EndsWith(".csv"))
            {
                connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='text;HDR=YES;FMT=Delimited';";
                strSql = "select * from " + name;
            }
            else
            {
                return null;
            }
            DataSet ds = null;
            OleDbConnection conn = null;
            try
            {
                conn = new OleDbConnection(connstring);
                conn.Open();
                OleDbDataAdapter myCommand = null;

                myCommand = new OleDbDataAdapter(strSql, connstring);
                ds = new DataSet();
                myCommand.Fill(ds, "table1");
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }
            return ds;
        }