zoukankan      html  css  js  c++  java
  • c#导入excel 绑定数据 repeat为例子

    先读取Excel文件并存到dataset 

     1 public DataSet ExcelToDataTable(string filename, string strsheetname)
     2     {
     3         try
     4         {
     5             //源的定义
     6             string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
     7 
     8             //Sql语句
     9             string strExcel = string.Format("select * from [{0}$]", strsheetname);
    10             //string strExcel = "select * from   [sheet1$]";
    11 
    12             //定义存放的数据表
    13             DataSet ds = new DataSet();
    14 
    15             //连接数据源
    16             OleDbConnection conn = new OleDbConnection(strConn);
    17 
    18             conn.Open();
    19 
    20             //适配到数据源
    21             OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
    22             adapter.Fill(ds, strsheetname);
    23 
    24             conn.Close();
    25 
    26             //return ds.Tables[strsheetname];
    27             return ds;
    28         }
    29         catch (Exception err)
    30         {
    31             throw new Exception("数据绑定Excel失败!失败原因:" + err.Message);
    32 
    33         }  
    34     }

    然后绑定:

    1 string fileName = fileUpload.PostedFile.FileName;
    2 DataSet ds = ExcelToDataTable(fileName, "sheet1");
    3 
    4 
    5 rptTab.DataSource = ds.Tables[0];
    6 rptTab.DataBind();

    需要注意的是    连接字符串中 

    HDR =  Yes  意思是把读取数据的第一行作为数据字段绑定,默认就是YES  不需要的可以把这个设置为NO
  • 相关阅读:
    安装pipenv
    ModuleNotFoundError: No module named 'pip._internal' , pip 无法下载软件 解决办法
    1.3用户列表 and 新闻列表
    1.2用户统计页面实现
    1.5发布新闻
    七牛云平台(存储图片)
    1.2头像设置功能
    1.4用户收藏展示
    1.3密码修改
    1.2首页刷新以及点击排行
  • 原文地址:https://www.cnblogs.com/mandalaluo/p/3835108.html
Copyright © 2011-2022 走看看