using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Data.OleDb;
public partial class Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
Bind(); //窗体加载时向GridView中填充数据
}
}
PosDataContext pos = new PosDataContext(); //使用Linq to sql进行操作数据库的数据
//自定义向GridView控件填充数据方法
private void Bind()
{
GridView1.DataSource = pos.Product.ToList(); //填充数据
GridView1.DataKeyNames = new string[] {"Id" }; //设置主键字段
GridView1.DataBind(); //将数据绑定到控件中
}
//导出数据事件
protected void btnExcel_Click(object sender, EventArgs e)
{
Export("application/ms-excel","商品信息报表.xls");
}
//自定义导出数据的方法
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312"; //设置获取输出数据的类型
Response.ContentEncoding = System.Text.Encoding.UTF7;
//将Http头添加到输出流
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw); //将GridView中的内容输出到指定字符串中
Response.Write(tw.ToString());
Response.End(); //将当前面的所有缓冲发送到客户端
}
//如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
//将Excel中的数据导入到指定控件中
public DataSet CreateDataSource() {
string strCon = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Excel.xls")+"; Extended Properties= Excle 8.0";
OleDbConnection olecon=new OleDbConnection(strCon);
OleDbDataAdapter myda=new OleDbDataAdapter("select * from [Sheet1$]",strCon);
DataSet myds=new DataSet();
myda.Fill(myds);
return myds;
}
//将数据从Excel导入到指定控件中
protected void btnExcelInfo_Click(object sender, EventArgs e)
{
GridView1.DataSource= CreateDataSource();
GridView1.DataBind();
}
}
使用GridView将数据导入或导出Excel中
最新推荐文章于 2014-06-03 17:29:54 发布
本文介绍了如何在ASP.NET Web应用程序中使用Linq to SQL进行数据库操作,并通过GridView控件展示数据。同时,实现了一个自定义方法用于将数据导出为Excel文件,方便数据管理和分享。
932

被折叠的 条评论
为什么被折叠?



