现在的位置: 首页 > 综合 > 正文

.NET导入Excel数据

2013年01月01日 ⁄ 综合 ⁄ 共 4650字 ⁄ 字号 评论关闭

本文转自:http://www.cnblogs.com/shuang121/archive/2011/05/13/2045446.html

 

有些时候我们需要批量添加数据,如果我们直接使用添加功能添加会很繁琐,而且如果数据没了,还要这样添加,这样显然是不好的,所以我们可以先把数据记录在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;";

        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>");
            }
  

    }

 

抱歉!评论已关闭.