.net导入Excel文件返回DataSet数据集

        #region 获取数据集
        protected DataSet GetDataSet(string filePath)
        {
            //2010以前版本连接字符串  
            //string Connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");    

            //IMEX=1 一共有三种模式 0表示导出 1 导入 2表示混合模式 在读取Excel数据有金额类型的后面带小数点最好去掉IMEX属性    
            //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES  
            string Connstr2010 = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Server.MapPath("~/") + filePath + "';Extended Properties='Excel 12.0;HDR=NO'");
            OleDbConnection Conn = new OleDbConnection(Connstr2010);
            //创建ArrayList对象 存放所有sheetname      
            ArrayList sheetNamelist = new ArrayList();
            DataSet dsExcel = new DataSet();
            try
            {
                if (Conn.State == ConnectionState.Closed)//检测conn是否处于开启状态
                {
                    Conn.Open();
                }
                DataTable dtExcelSchema = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });


                string sheetName = string.Empty;

                for (int j = 0; j < dtExcelSchema.Rows.Count; j++)
                {

                    sheetName = dtExcelSchema.Rows[j]["TABLE_NAME"].ToString();
                    //sheet名称   
                    if (sheetName.ToLower().IndexOf("database") != -1)
                        continue;
                    else
                        sheetNamelist.Add(sheetName);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString(), ex);
            }
            finally
            {
                Conn.Close();
            }
            try
            {
                string strSQL = string.Empty;
                for (int i = 0; i < sheetNamelist.Count; i++)
                {

                    strSQL = "select * from [" + sheetNamelist[i].ToString() + "]";
                    OleDbDataAdapter da = new OleDbDataAdapter(strSQL, Conn);
                    DataTable dtExcel = new DataTable(sheetNamelist[i].ToString());
                    da.Fill(dtExcel);

                    dsExcel.Tables.Add(dtExcel);
                }

                return dsExcel;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString(), ex);
                return null;
            }
            finally
            {

            }
        }
        #endregion

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值