zoukankan      html  css  js  c++  java
  • .NET导入Excel数据

          有些时候我们需要批量添加数据,如果我们直接使用添加功能添加会很繁琐,而且如果数据没了,还要这样添加,这样显然是不好的,所以我们可以先把数据记录在excel中,直接导入即可,还可以重用,不用一个一个添加,这样可以解决不少的时间,现在我们来看看如何在.net中导入excel数据!

         大致的步骤是这样的:

         首先,我们要在excel中添加好数据,保存好

         其次,excel文件导入到项目中的指定文件夹下,然后读取excel中的数据到内存中(DataTable)

         最后,从dataTable中取出这些数据添加到指定的数据库表里即可

       下面来看一个具体的例子:

       

    View Code
      //查询excel的方式
      public DataSet ExecleDs(string filenameurl, string table)
        {

            DataSet ds 
    = new DataSet();

                  string strConn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + filenameurl + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";

            OleDbConnection conn 
    = new OleDbConnection(strConn);

            conn.Open(); 
            
            
    string tableName=conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();

            OleDbDataAdapter odda 
    = new OleDbDataAdapter("select * from ["+tableName+"]",conn);

            odda.Fill(ds, table);

            
    return ds;

        }

       //讲excel添加到项目中,并读取数据到数据库表中
        
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {

            
    if (banji.SelectedValue == "0")
            { 
            Response.Write(
    "<script>alert('请选择班级!')</script>");   //当Excel表为空时,对用户进行提示
            return;
            }
           
            
    int ccid = Convert.ToInt32(banji.SelectedValue);
            
            
    if (FileUpload1.HasFile == false)//HasFile用来检查FileUpload是否有指定文件
            {
                Response.Write(
    "<script>alert('请您选择Excel文件')</script> ");
                
    return;//当无文件时,返回
            }
            
    string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名
            if (IsXls != ".xls")
            {
                Response.Write(
    "<script>alert('只可以选择Excel文件')</script>");
                
    return;//当选择的不是Excel文件时,返回
            }
          
                
    string filename = FileUpload1.FileName;              //获取Execle文件名  DateTime日期函数
                string savePath = Server.MapPath(("~\\CourseFile\\"+ filename);//Server.MapPath 获得虚拟服务器相对路径
                FileUpload1.SaveAs(savePath);                        //SaveAs 将上传的文件内容保存在服务器上
                DataSet ds = new DataSet();
                
    try
                {
                     ds 
    = ExecleDs(savePath, filename);
                }
                
    catch 
                {
                    Response.Write(
    "<script>alert('导入失败,Excel工作表标签名错误,标签名必须是Sheet1,请查证后再导入!')</script>");
                    
    return;
                }

                
    //DataRow dr = ds.Tables[0].Rows;            //定义一个DataRow数组
                int rowsnum = ds.Tables[0].Rows.Count;
               
                
    if (rowsnum ==0)
                {
                    Response.Write(
    "<script>alert('Excel表为空表,无数据!')</script>");   //当Excel表为空时,对用户进行提示
                    return;
                }
                
    else
                {
                    
    for (int i = 0; i < rowsnum; i++)
                    {

                        M_CZUser mu 
    = new M_CZUser();
                        B_CZUser bu 
    = new B_CZUser();
                         
    try
                        {
                            mu.userid 
    = ds.Tables[0].Rows[i]["帐号"].ToString();
                            mu.pwd 
    = ds.Tables[0].Rows[i]["密码"].ToString();
                            mu.uname 
    = ds.Tables[0].Rows[i]["姓名"].ToString();
                            mu.num 
    = ds.Tables[0].Rows[i]["学号"].ToString();//日期 excel列名【名称不能变,否则就会出错】
                            mu.sex = ds.Tables[0].Rows[i]["性别"].ToString();
                        mu.utype 
    = 4;
                        mu.class_id 
    = ccid;
                        mu.birthday 
    = DateTime.Parse(ds.Tables[0].Rows[i]["出生日期"].ToString());
                        mu.Lastlogintime 
    = DateTime.Now;
                        mu.idcard 
    = ds.Tables[0].Rows[i]["身份证号码"].ToString();
                        DataSet ds2 
    = bu.GetList("*""userid='" + ds.Tables[0].Rows[i]["帐号"].ToString() + "'");
                        
    if (ds2.Tables[0].Rows.Count > 0)
                        {
                            Function.showmessage(
    this.Page, "帐号" + ds.Tables[0].Rows[i]["帐号"].ToString() + "已存在,操作终止。""""");
                            
    return;
                        }
                        DataSet ds3 
    = bu.GetList("*""num='" + ds.Tables[0].Rows[i]["学号"].ToString() + "'");
                        
    if (ds3.Tables[0].Rows.Count > 0)
                        {
                            Function.showmessage(
    this.Page, "学号" + ds.Tables[0].Rows[i]["学号"].ToString() + "已存在。""""");
                            
    return;
                        }
                            bu.Add(mu);
                        }
                        
    catch (Exception ex)       //捕捉异常
                        {
                            Response.Write(
    "<script>alert('导入内容:" + ex.Message + "')</script>");
                            
    return;
                        }

                    }
                    Response.Write(
    "<script>alert('Excle表导入成功!')</script>");
                }
      

        }
    Excel其实也是一种数据库,既然是数据库,就可以用一般的操作数据库的方法来做处理。
             /// <summary>
            /// 包含表头的连接
            /// </summary>
            private  const string EXCELCONNECTIN = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';";
            /// <summary>
            /// 不包含表头的连接
            /// </summary>
            private  const string EXCELCONNECTINNOHDR = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;HDR=NO;IMEX=1;';";
    一般的情况下,还是使用包含表头的连接,否则会出现,导入到数据库的时候,有些字段的值是空的
    多思考,多创新,才是正道!
  • 相关阅读:
    springboot项目前端页面中文搜索时,数据库查询为空(mysql)
    Eclipse修改项目包名
    eclipse中maven父子项目层级显示设置
    springboot整合pagehelper实现分页
    eclipse设置文档注释
    永久修改mysql时区
    前端页面展示时间与数据库时间相差8小时(mysql)
    前端页面展示时间与数据库时间相差5小时(mysql)
    AxureRP 9安装、激活、汉化
    PowerDesigner 16.5安装、激活
  • 原文地址:https://www.cnblogs.com/shuang121/p/2045446.html
Copyright © 2011-2022 走看看