从Excel导入到GridView,导入到数据库

本文介绍了一种将Excel文件上传并转换为数据库表的方法。通过使用ADO.NET技术读取Excel文件,并利用SqlBulkCopy批量插入数据到SQL Server中。文章详细展示了如何验证文件类型、读取Excel内容、设置连接字符串及完成数据导入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   SqlC sc = new SqlC();
    public string fileName;
    public string serverPath;
    public string filePath;

    public void EtoG(string sql)
    {
        filePath = this.FileUpload1.PostedFile.FileName;//获取上传文件的路经;
        fileName = filePath.Substring(filePath.LastIndexOf("//") + 1);//或得文件名;
        string fileExtend = filePath.Substring(filePath.LastIndexOf(".") + 1);//或得扩展名;
        if (fileExtend != "xls")//判断是否是xls文件
        {
            Response.Write("不是xls文件,请选择xls文件!!");
            Response.End();
        }
        serverPath = Server.MapPath("excel") + "//" + fileName;//把文件保存到服务器上指定的路经
        this.FileUpload1.SaveAs(serverPath);//保存文件到服务器上
        serverPath = Server.MapPath("excel") + "//" + fileName;//把文件保存到服务器上指定的路经
        this.FileUpload1.SaveAs(serverPath);//保存文件到服务器上
        string strCon;
        strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + serverPath + "; Extended Properties=Excel 8.0;";

        OleDbConnection ole = new OleDbConnection(strCon);
        ole.Open();
        OleDbDataAdapter da = new OleDbDataAdapter(sql, strCon);
        DataSet ds = new DataSet();
        da.Fill(ds);
        ole.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind();

    }

        string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + serverPath + "; Extended Properties=Excel 8.0;";
        string strExcel = string.Format("select * from [sheet$]", fileName);
        OleDbDataAdapter da1 = new OleDbDataAdapter(strExcel, strCon);
        DataSet ds1 = new DataSet();
        da1.Fill(ds1, fileName);
        SqlBulkCopy bcp = new SqlBulkCopy("Server=localhost;DataBase=Keyantongji ;Integrated Security =SSPI");
        bcp.SqlRowsCopied += new SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
        bcp.BatchSize = 100;
        bcp.NotifyAfter = 100;
        bcp.DestinationTableName = 目标表
        bcp.WriteToServer(ds1.Tables[0]);

    void bcp_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
    {
        throw new Exception("The method or operation is not implemented.");              
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值