protected void buts_Click(object sender, EventArgs e)
{
//清除客户端当前显示
Response.Clear();
//作为附件输出,filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
Response.AddHeader("content-disposition", "attachment;filename=agentno_download_YYYYMMDD.xls"); //显示标头
//设置显示的字和内容要存的形式
Response.Charset = "gb2312";
Response.ContentType = "application/vnd.xls";
//Response.ContentType = "application/octet-stream";(此句适合任何文件类型)
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
this.GridView1.Columns[0].Visible = false;//使第一列修改不会导入进去
this.GridView1.Columns[1].Visible = false;//使第二列删除不会导入进去
GridView1.AllowPaging = false;
Bind();
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
GridView1.AllowPaging = true;
Bind();
}
2.必须要的方法(如果没有这个方法就回报错)
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
3.绑定gridview方法:
public DataTable dt = null;
protected void Bind()
{
string strSql = "select * from Book";
using (SqlConnection conn = new SqlConnection("server=192.168.30.246;database=stuDB;user id=sa;password=sa;pooling=true;"))
{
using (SqlDataAdapter da = new SqlDataAdapter(strSql, conn))
{
try
{
conn.Open();
dt = new DataTable();
da.Fill(dt);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
catch(Exception err)
{
throw new Exception("错误信息如下:"+err.Message.ToString());
}
}
}
}
4.如果不是管理员那么不能删除/添加/修改等操作
if (!Common.IsManager(Session["userid"].ToString()))
{
this.GridView1.Columns[0].Visible = false;
this.GridView1.Columns[1].Visible = false;
this.addbut.Visible = false;
this.baobiao.Visible = false;
}
5.导入时格式的转换:
protected void gError_RowDataBound(object sender, GridViewRowEventArgs e)
{
//1) 文本:vnd.ms-excel.numberformat:@
//2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
//3) 数字:vnd.ms-excel.numberformat:#,##0.00
//4) 货币:vnd.ms-excel.numberformat:¥#,##0.00
//5) 百分比:vnd.ms-excel.numberformat: #0.00%
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
e.Row.Cells[i ].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
}