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:@");
}
}