protected void btnExcel_Click(object sender, EventArgs e)
{
if (Session["strWhere"] == null)
{
MessageBox.Show(this, "请先查询,再导出EXCEL");
return;
}
gvHYXF.DataSource = (object)bll.BindData(Session["strWhere"].ToString()); //为GridView绑定数据
gvHYXF.DataBind();
DataGrid n = new DataGrid();
DataSet dsn = new DataSet();
dsn = ChangeC(bll.BindData(Session["strWhere"].ToString()), gvHYXF);
this.DataGridToExcel(n, dsn);
}
//下面这两个函数完全不用修改,可以直接拷贝到程序里面,只要传给他们正确的DataSet 和 GridView即可
//如果报异常的话,可能是前台GridView的FooterText没有设置
private DataSet ChangeC(DataSet ds, GridView gv)
{
Hashtable hstb = new Hashtable();
for (int j = 0; j < gv.Columns.Count; j++)
{
hstb.Add(gv.Columns[j].FooterText, gv.Columns[j].HeaderText);
}
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
if (hstb[ds.Tables[0].Columns[i].ColumnName] != null)
{
ds.Tables[0].Columns[i].ColumnName = hstb[ds.Tables[0].Columns[i].ColumnName].ToString();
}
}
return ds;
}
protected void DataGridToExcel(DataGrid grdTemp, DataSet dsTemp)
{
grdTemp.AllowPaging = false; //设置不能分页
grdTemp.DataSource = dsTemp; //重新绑定数据源
grdTemp.DataBind();
//常规导出方法
System.IO.StringWriter SW = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter HTW = new System.Web.UI.HtmlTextWriter(SW);
grdTemp.RenderControl(HTW);
//Page为要导出的对象,当前是Page,如果是DataGrid,DataList等都可以
Response.Buffer = true;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-excel ";
//Response.ContentType是输出流的 HTTP MIME 类型
//Response.ContentType --- word文件
//application/vnd.ms-excel --- excel文件
//...
Response.Charset = "utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.AddHeader("Content-Disposition", "attachment;filename=hyxx.xls");
//attachment --- 作为附件下载
//inline --- 在线打开
//filename如过是中文,则可以用HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)
//进行进行编码,以解决文件名乱码的问题
Response.Write(SW.ToString());
Response.Flush();
Response.Close();
}