导出数据表到文件(excel、word等)

来源:互联网 发布:用户提高淘宝搜索质量 编辑:程序博客网 时间:2024/05/20 03:07
 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);//动态定义GridViewGridView 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:@;");//参数自选}}