zoukankan      html  css  js  c++  java
  • 将Excl 中的数据读入到GridView中

    现我们来看看代码:

    protected void Button1_Click(object sender, EventArgs e)//读取按钮事件
        {
            
    this.GridView1.DataSource = CreateDataSource();
            
    this.GridView1.DataBind();
        }
    private DataSet CreateDataSource()
        {
            
    string strCon;
            
    //用excel作为数据源 ,Server.MapPath("Book1.xls")中这个Book1.xls文件已经在服务器内,且目录与当前cs文件目录相同
            strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Book1.xls"+ ";Extended Properties=Excel 8.0;";
            OleDbConnection conn 
    = new OleDbConnection(strCon);
            OleDbDataAdapter myda 
    = new OleDbDataAdapter("select * from [Sheet1$]", strCon);
            DataSet myds 
    = new DataSet();
            myda.Fill(myds);
            
    return myds;
        }

    在实际应用中,我们可以用一个上传控件,把用户要显示的xls读取到服务器文件夹内,然再将它读到GridView中。

    PS:上例中的Server.MapPath("")是用来读取服务器中的xls文件,如果文件不在服务器中也是能读到的,比如就在

    用户的本地磁盘也行,代码可作如下改动:

     private DataSet CreateDataSource()
        {
            
    string filePath = "";
            
    if (FJ.PostedFile.FileName == "")
            {
                Response.Write(
    "<script language=javascript>alert('请选择要上传的文件!');</script>");
                
    return null;
            }
            
    else
            {
                filePath 
    = FJ.PostedFile.FileName;//取得文件路径
                string strCon;
                strCon 
    = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +filePath+ ";Extended Properties=Excel 8.0;";
                OleDbConnection conn 
    = new OleDbConnection(strCon);
                OleDbDataAdapter myda 
    = new OleDbDataAdapter("select * from [Sheet1$]", strCon);
                DataSet myds 
    = new DataSet();
                myda.Fill(myds);
                
    return myds;
            }
        }

    filePath 就直接是用户本地磁盘上的路径了。操作完成后,服务器中并没有这个xls文件。

    还有就是如果要将数据再读入到数据库中就可以去操作那个dataset了,因为数据是先读到dst中的,可以去读取dst中表的每条记录,

    然后再插入到数据库中保存.

  • 相关阅读:
    netcore跨域
    阿里云oss通过api上传图片后不能预览只能下载的解决方法
    阿里云oss对图片的处理:缩略、剪裁、锐化等
    通过字节值判断图片格式
    Linux 常见命令 用户管理命令(二)
    nohup命令
    selinux基础介绍
    LINUX中的limits.conf配置文件
    【ASP.NET】使用Jquery缓存数据
    .net 4.0以下版本实现web socket服务
  • 原文地址:https://www.cnblogs.com/wantingqiang/p/1307341.html
Copyright © 2011-2022 走看看