A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-9-13 22:36  /  1466 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

这篇文章主要介绍了asp.net读取excel中的数据并绑定在gridview上的方法,需要的朋友可以参考下
前台label,DropDownList,gridview控件

aspx.cs核心代码:

  1. using System.Data.OleDb;//需要引入命名
  2. public void Excel_Click(object sender, EventArgs e)
  3. {
  4. if (this.AttachmentFile.Value == "" && this.Label1.Text == "" && DropDownList2.SelectedValue == "")
  5. {
  6. Response.Write("<script>window.alert('请选择要导入的文件')</script>");
  7. }
  8. if (this.AttachmentFile.Value != "" && this.DropDownList2.SelectedValue == "")
  9. {
  10. HttpFileCollection files = HttpContext.Current.Request.Files;
  11. HttpPostedFile postedFile = files[0];
  12. fileName = System.IO.Path.GetFileName(postedFile.FileName);
  13. if (fileName != "")
  14. {
  15. postedFile.SaveAs("\\\\localhost\\文件夹\\" + fileName);
  16. }
  17. string strConn;
  18. strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "\\\\localhost\\文件夹\\" + fileName + ";Extended Properties=Excel 8.0;";//this.AttachmentFile.Value.ToString()
  19. OleDbConnection conn = new OleDbConnection(strConn);
  20. conn.Open();
  21. DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  22. foreach (DataRow dr in sheetNames.Rows)
  23. {
  24. DropDownList2.Items.Add(dr[2].ToString());
  25. }
  26. this.Label1.Text = "\\\\localhost\\文件夹\\" + fileName;//this.AttachmentFile.Value.ToString();
  27. conn.Close();
  28. }
  29. if (this.Label1.Text.ToString() != "" && this.DropDownList2.SelectedValue != "")// && this.DropDownList1.SelectedValue.ToString() != "全部"
  30. {

  31. //绑定到gridview
  32. GridView1.DataSource = createDataSource(DropDownList2.SelectedValue.ToString(), this.Label1.Text.ToString());//, this.DropDownList1.SelectedValue.ToString()
  33. GridView1.DataBind();


  34. }


  35. }
  36. //以Excel为数据源获取数据集
  37. private DataSet createDataSource(string select, string lable)

  38. {
  39. string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + lable + ";Extended Properties=Excel 8.0;";
  40. string strsql = "select 登记号码,姓名,日期,签到时间,签退时间,部门 from [" + select + "] order by 部门,日期,姓名";//excel表格的字段
  41. OleDbConnection conn = new OleDbConnection(strCon);
  42. OleDbDataAdapter da = new OleDbDataAdapter(strsql, conn);
  43. try
  44. {
  45. conn.Open();
  46. DataSet ds = new DataSet();
  47. da.Fill(ds);
  48. conn.Close();
  49. return ds;
  50. }
  51. catch (Exception e)
  52. {
  53. Response.Write("<script>window.alert('没有数据,或者" + e.Message + "')</script>");
  54. return null;
  55. }
  56. }
复制代码

以上是插入07以前版本excel

如果07版本以后只需要做小小修改

  1. string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + lable + ";Extended Properties=Excel 12.0;";
复制代码

1 个回复

倒序浏览
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马