GridView中的数据导出到Excel方法(包含处理模板列)
来源:互联网 发布:文明4for mac配置要求 编辑:程序博客网 时间:2024/06/17 03:16
- GridView中的数据导出到Excel方法(包含处理模板列)收藏
- 新一篇: 关于js日期控件 | 旧一篇: 55种网页常用小技巧
- 今天再整理一篇有用的文章,对于GridView中数据的导出的处理问题。有时我们在GridView表格中显示的不仅仅是从数据库中读出的值,还需要加上一些人为处理的模板列(比如删除按钮、下拉选择框、hypelinker等)。在导出后,我们往往不需要这些控件显示或者不希望以控件的形式来显示,而是以数据的形式来展示。这就需要在导出时作一些处理,参考了一些互联网上的信息,整理如下:
- 一、导出button
- protected void export_Click(object sender, EventArgs e)
- {
- if (this.MachineList.Rows.Count == 0)
- {
- Response.Write("<script>alert('没有查找到数据,无法导出!')</script>");
- }
- else
- {
- this.MachineList.AllowPaging = false;
- Bind();
- Export("application/ms-excel", "设备信息.xls");
-
- this.MachineList.AllowPaging = true;
- Bind();
- }
- }
- 二、导出主函数
- public void Export(string FileType, string FileName)
- {
- string style = @"<style>.text{mso-number-format:@}</script>";
- PrepareGridViewForExport(MachineList);
- Response.Clear();
- Response.Charset = "GB2312";
- Response.ContentEncoding = Encoding.UTF7;
- Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
- Response.ContentType = FileType;
- this.EnableViewState = false;
- this.MachineList.AllowPaging = false;
- System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
- StringWriter sw = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(sw);
- this.MachineList.RenderControl(htw);
- Response.Write(style);
- Response.Write(sw.ToString());
-
- Response.End();
- }
-
-
-
-
-
-
-
-
-
- public override void VerifyRenderingInServerForm(Control control)
- {
-
-
- }
- 三、如果GridView存在模板列,其中包含子控件,例如CheckBox等,导出EXCEL后就会出现该区域的不规律。所以要对模板列单独处理(转载)
- public void PrepareGridViewForExport(Control gv)
- {
- LinkButton lb = new LinkButton();
- Literal l = new Literal();
- string name = String.Empty;
- for (int i = 0; i < gv.Controls.Count; i++)
- {
-
- if (gv.Controls[i].GetType() == typeof(LinkButton))
- {
- l.Text = (gv.Controls[i] as LinkButton).Text;
- gv.Controls.Remove(gv.Controls[i]);
- gv.Controls.AddAt(i, l);
- }
- else if (gv.Controls[i].GetType() == typeof(DropDownList))
- {
- l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
- gv.Controls.Remove(gv.Controls[i]);
- gv.Controls.AddAt(i, l);
- }
- else if (gv.Controls[i].GetType() == typeof(CheckBox))
- {
- l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
- gv.Controls.Remove(gv.Controls[i]);
- gv.Controls.AddAt(i, l);
- }
- else if (gv.Controls[i].GetType() == typeof(ImageButton))
- {
- l.Text = "图片";
- gv.Controls.Remove(gv.Controls[i]);
- gv.Controls.AddAt(i, l);
- }
- if (gv.Controls[i].HasControls())
- {
- PrepareGridViewForExport(gv.Controls[i]);
- }
- }
- }
- 注:对于模板列的处理还有一特殊情况,我在GridView使用时,用了<a></a>在客户端打开对话框的方法。在导出时,这一列不是模板列控件,但导出后Excel中会显示有下划线的链接,所以想去掉它。
- 想了很多方法,也没成功。后来我只好用了不得以的方法,多加一列文本列,用来显示链接的文本,导出前采用列隐藏的方法解决。
- 如果有更好的处理方法,也请各位指教!