【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable



OleDbDataAdapter方式:

        /// <summary>
        /// 读取excel的表格放到DataTable中 ---OleDbDataAdapter 
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="excelpath">excel路径</param>
        /// <returns>datatable</returns>
    public static DataTable readexcel(string excelpath,string strSql)
        {
            OleDbConnection objConn = null;
            DataTable dt = new DataTable();
            try
            {
                string excelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + excelpath + ";Excel 8.0;HDR=NO;IMEX=1";//HDR=YES第一行是标题,NO第一行不是标题;IMEX=1表示导入模式,这个模式开启的 Excel 档案只能用来做“写入”用途,还有个重要作用:强制将混合数据转换为文本,可读出excel的数字型的内容。
                objConn = new OleDbConnection(excelConn);
                objConn.Open();
                OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
                OleDbDataAdapter adr = new OleDbDataAdapter();
                adr.SelectCommand = objCmd;
                adr.Fill(dt);
                objConn.Close();
                return dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

OleDbDataReader 方式:

        /// <summary>
        /// 读取excel的表格放到DataTable中 ---OleDbDataReader 
        /// </summary>
        /// <param name="strSql"></param>
        /// <param name="excelpath">excel路径</param>
        /// <returns>datatable</returns>
     public static DataTable readexcel(string excelpath,string strSql)
     {
         string excelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + excelpath + ";Excel 8.0;HDR=NO;IMEX=1";//HDR=YES第一行是标题,NO第一行不是标题;IMEX=1表示导入模式,这个模式开启的 Excel 档案只能用来做“写入”用途,还有个重要作用:强制将混合数据转换为文本,可读出excel的数字型的内容。
         DataTable dt = new DataTable();
         try
         {
             using (OleDbConnection connection = new OleDbConnection(excelConn))
             {
                 OleDbCommand command = new OleDbCommand(strSql, connection);
                 connection.Open();
                 OleDbDataReader reader;
                 reader = command.ExecuteReader();
                 dt.Load(reader); //直接把reader转换为datatable
                 reader.Close();
             }
             return dt;
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
             return null;
         }
     }

从上述两个例子不难看出,其实excel也相当于一个数据库,读取excel的sql语句如:string strSql = "Select  *  From  [sheet1$A10:L24]";//读取sheet1工作表A10到L24区域的内容

类似的,读取oracle等数据库,只需把数据库引擎等改为相应的类型就可以了。



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值