Asp.net操作Excel的例子包括添加 修改 检索 导出 已调试通过可以直接使用

Asp.net操作Excel的例子包括添加 修改 检索 导出 已调试通过可以直接使用

private void Data_Bind()
  {//检索程式
   //比如我们要检索A1到D20的所有数据,可以这样检索:SELECT * FROM [SampleSheet$A1:D20],这里,使用A1:D20来限制检索范围。
   //如果数据表第一行已经定义数据列的名字,我们可以选择需要显示的数据列来检索:SELECT 姓名 FROM [First$A1:B2]
   OleDbConnection conn=new OleDbConnection();
   conn.ConnectionString="provider=Microsoft.jet.OLEDB.4.0;Data Source="+Server.MapPath("DataBase.xls")+";Extended Properties=Excel 8.0;";
   string sql="SELECT * FROM [Sheet1$]";
   OleDbDataAdapter cmd=new OleDbDataAdapter(sql,conn);
   DataSet ds=new DataSet();
   cmd.Fill(ds,"DataTable1");
   xlsData.DataSource=ds.Tables["DataTable1"];
   xlsData.DataBind();
  } 

  private void show_Click(object sender, System.EventArgs e)
  {//检索
   Data_Bind();
  }

  private void add_Click(object sender, System.EventArgs e)
  {//添加
   Add_Xls();
  }
  private void Add_Xls(){//添加程式
  OleDbConnection conn=new OleDbConnection();
   conn.ConnectionString="provider=Microsoft.jet.oledb.4.0;Data Source="+Server.MapPath("DataBase.xls")+";Extended Properties=Excel 8.0;";
   conn.Open();
   string sql="insert into [Sheet1$](用户名,密码,ID)values('金勋男','11111111','6')";
   OleDbCommand cmd=new OleDbCommand(sql,conn);
   cmd.ExecuteNonQuery();
   cmd.Dispose();
   conn.Close();
   conn.Dispose();
   Data_Bind();
  }

  private void modify_Click(object sender, System.EventArgs e)
  {//修改
  Modify_Xls();
  }
  private void Modify_Xls(){
  //修改程式
   OleDbConnection conn=new OleDbConnection();
   conn.ConnectionString="provider=Microsoft.jet.oledb.4.0;Data Source="+Server.MapPath("DataBase.xls")+";Extended Properties=Excel 8.0;";
   conn.Open();
   string sql="update [Sheet1$] set 密码=88888888 where 用户名='宋倩'";
   OleDbCommand cmd=new OleDbCommand(sql,conn);
   cmd.ExecuteNonQuery();
   cmd.Dispose();
   conn.Close();
   conn.Dispose();
   Data_Bind();
  }
  private void emport_Click(object sender, System.EventArgs e)
  {//导出   
   ToExcel(xlsData);
  }
  
  public void ToExcel(System.Web.UI.Control ctl)
  { //通过DataGrid导出Xls程式
   HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
   HttpContext.Current.Response.Charset ="UTF-8";
   HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
   HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
   ctl.Page.EnableViewState =false;
   System.IO.StringWriter tw = new System.IO.StringWriter() ;
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
   ctl.RenderControl(hw);
   HttpContext.Current.Response.Write(tw.ToString());
   HttpContext.Current.Response.End();
  }

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值