protected void Export_Click(object sender, EventArgs e)
{ //button_Click事件
//……
//……
ExportExcel(dateSet.Tables[0],"application/ms-excel", "FileName.xls","TableName");
//……
//……
}
/// <summary>
/// 此方法必重写,否则会出错
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
{
}
/// <summary>
/// 导出数据到文件
/// </summary>
/// <param name="table">数据源</param>
/// <param name="FileType">导出的文件类型(application/ms-word | application/ms-excel
/// | application/ms-txt | application/ms-html 或其他浏览器可直接支持文档)</param>
/// <param name="FileName">导出的文件名,自己填写文件名</param>
/// <param name="tableName">导出到文件中的表名</param>
private void ExportExcel(DataTable table, string FileType, string FileName,string tableName)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
// attachment 参数表示作为附件下载, online在线打开
Response.AppendHeader("Content-Disposition", "attachment;filename="
+ HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter strWriter = new StringWriter();
HtmlTextWriter htmlTxtWriter = new HtmlTextWriter(strWriter);
//动态定义GridView
GridView gv = new GridView();
gv.RowDataBound += new GridViewRowEventHandler(this.gv_RowDataBound); //增加数据行绑定方法,修改格式
//格式化需要的属性
gv.AllowPaging = false; //必须不分页,否则出错
gv.AllowSorting = false;
gv.AutoGenerateDeleteButton = false; //取消控制按钮
gv.AutoGenerateEditButton = false;
gv.AutoGenerateSelectButton = false;
gv.CellPadding = 3; //间距
gv.ShowFooter = false; //表尾
gv.CaptionAlign = TableCaptionAlign.NotSet; //表标题
gv.Caption = tableName;
gv.Style.Add("Font-Size", "14px"); //style
//gv.……
//…… 需要的属性(style)设置,如字体,颜色,背景
//绑定数据
gv.DataSource = table;
gv.DataBind();
//写入
gv.RenderControl(htmlTxtWriter);
Response.Output.Write(strWriter.ToString());
Response.Flush();
Response.End();
}
private void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{ //绑定行数据
foreach (TableCell tc in e.Row.Cells)
{ //格式化每个单元格
tc.Attributes.Add("style", "vnd.ms-excel.numberformat:@;"); //参数自选
}
}导出数据表到文件(excel、word等)
最新推荐文章于 2024-10-26 12:38:22 发布
本文详细介绍了如何使用ASP.NET实现将数据导出为Excel文件,并提供了代码示例。
1694

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



