DataGrid 完全攻略之二(把数据导出到Excel)

简介:

前台代码:html
<% @ Page language="c#" Codebehind="ExportExcel.aspx.cs" AutoEventWireup="false" Inherits="MsDataGrid.ExportExcel"  %>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"  >
< HTML >
    
< HEAD >
        
< title > DataGrid使用举例 </ title >
        
< meta  name ="GENERATOR"  Content ="Microsoft Visual Studio 7.0" >
        
< meta  name ="CODE_LANGUAGE"  Content ="C#" >
        
< meta  name ="vs_defaultClientScript"  content ="JavaScript" >
        
< meta  name ="vs_targetSchema"  content ="http://schemas.microsoft.com/intellisense/ie5" >
    
</ HEAD >
    
< body  MS_POSITIONING ="GridLayout" >
        
< form  id ="Form1"  method ="post"  runat ="server" >
            
< FONT  face ="宋体" >
                
< asp:DataGrid  id ="dgShow"  style ="Z-INDEX: 100; LEFT: 26px; POSITION: absolute; TOP: 89px"  runat ="server"  Width ="842px"  Height ="172px"  BorderColor ="Tan"  BorderWidth ="1px"  BackColor ="LightGoldenrodYellow"  CellPadding ="2"  GridLines ="None"  ForeColor ="Black"  PageSize ="1"  AutoGenerateColumns ="False"  ShowFooter ="True"  AllowPaging ="True" >
                    
< SelectedItemStyle  ForeColor ="GhostWhite"  BackColor ="DarkSlateBlue" ></ SelectedItemStyle >
                    
< AlternatingItemStyle  BackColor ="PaleGoldenrod" ></ AlternatingItemStyle >
                    
< HeaderStyle  Font-Bold ="True"  BackColor ="Tan" ></ HeaderStyle >
                    
< FooterStyle  BackColor ="Tan" ></ FooterStyle >
                    
< Columns >
                        
< asp:BoundColumn  DataField ="StudentID"  ReadOnly ="True"  HeaderText ="学生ID" ></ asp:BoundColumn >
                        
< asp:BoundColumn  DataField ="StudentName"  HeaderText ="学生姓名" ></ asp:BoundColumn >
                        
< asp:BoundColumn  DataField ="StudentPass"  HeaderText ="密码" ></ asp:BoundColumn >
                        
< asp:BoundColumn  DataField ="Sex"  HeaderText ="性别" ></ asp:BoundColumn >
                        
< asp:BoundColumn  DataField ="Birthday"  HeaderText ="生日"  DataFormatString ="{0:yyyy-M-d}" ></ asp:BoundColumn >
                        
< asp:BoundColumn  DataField ="Email"  HeaderText ="邮件地址" ></ asp:BoundColumn >
                        
< asp:BoundColumn  DataField ="Score"  HeaderText ="分数" ></ asp:BoundColumn >
                        
< asp:ButtonColumn  Text ="选择"  CommandName ="Select" ></ asp:ButtonColumn >
                    
</ Columns >
                    
< PagerStyle  HorizontalAlign ="Center"  ForeColor ="DarkSlateBlue"  BackColor ="PaleGoldenrod"  Mode ="NumericPages" ></ PagerStyle >
                
</ asp:DataGrid >
                
< asp:Button  id ="btnMIME"  style ="Z-INDEX: 102; LEFT: 230px; POSITION: absolute; TOP: 44px"  runat ="server"  Text ="导出" ></ asp:Button ></ FONT >
        
</ form >
    
</ body >
</ HTML >

后台代码:cs
using  System;
using  System.Collections;
using  System.ComponentModel;
using  System.Data;
using  System.Drawing;
using  System.Web;
using  System.Web.SessionState;
using  System.Web.UI;
using  System.Web.UI.WebControls;
using  System.Web.UI.HtmlControls;
using  System.Data.SqlClient;
namespace  MsDataGrid
{
    
/// <summary>
    
/// WebForm1 的摘要说明。
    
/// </summary>

    public class ExportExcel : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Button btnMIME;
        
protected System.Web.UI.WebControls.DataGrid dgShow;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
            if(!IsPostBack)
                BindData();
            
            
        }

        
private void BindData()
        
{
            
string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
            SqlConnection con 
= new SqlConnection(strCon);
            SqlDataAdapter da 
= new SqlDataAdapter("Select * from tbStudentinfo",con);
            DataSet ds 
= new DataSet();
            da.Fill(ds,
"studentinfo");
            dgShow.DataSource 
= ds.Tables["studentinfo"].DefaultView;
            dgShow.DataBind();
            
        }

        
Web Form Designer generated code

        
private void btnMIME_Click(object sender, System.EventArgs e)
        
{
            Response.ContentType 
= "application/vnd.ms-excel";
            Response.Charset 
= "";
            
this.EnableViewState = false;
            System.IO.StringWriter sw 
= new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw 
= new System.Web.UI.HtmlTextWriter(sw);
            
int nCur = dgShow.CurrentPageIndex;
            
int nSize = dgShow.PageSize;
            
            dgShow.AllowPaging 
= false;
            BindData();
                
            dgShow.Columns[
7].Visible =false;
            dgShow.RenderControl(hw);
            dgShow.Columns[
7].Visible =true;
            
            
//以下恢复分页
            dgShow.AllowPaging = true;
            dgShow.CurrentPageIndex 
= nCur;
            dgShow.PageSize 
= nSize;
            BindData();
            Response.Write(sw.ToString());
            Response.End();
        }

    }

}

方法二:
if(DataGrid1.Items.Count==0)
    {
     Response.Write("<script>alert('对不起,你没有查询到任何记录,不能导出数据')</script>");
    }
    else
    {
      

     Response.Clear(); 
     Response.Buffer= true;
     Response.Charset="GB2312";
     Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls");
     Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
     //设置输出流为简体中文
     Response.ContentType = "application/ms-excel";
     //设置输出文件类型为excel文件。
     this.EnableViewState = false;
     System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true);
     System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
     System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
     DataGrid1.RenderControl(oHtmlTextWriter);
     Response.Write(oStringWriter.ToString());
     Response.End();

}
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
        // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
        Response.ContentEncoding = System.Text.Encoding.UTF7;
        Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        this.GridView1.RenderControl(oHtmlTextWriter); 
        Response.Output.Write(oStringWriter.ToString());
        Response.Flush();
        Response.End();




本文转自高海东博客园博客,原文链接:http://www.cnblogs.com/ghd258/archive/2005/10/12/253181.html,如需转载请自行联系原作者

相关文章
|
4月前
|
Python
如何根据Excel某列数据为依据分成一个新的工作表
在处理Excel数据时,我们常需要根据列值将数据分到不同的工作表或文件中。本文通过Python和VBA两种方法实现该操作:使用Python的`pandas`库按年级拆分为多个文件,再通过VBA宏按班级生成新的工作表,帮助高效整理复杂数据。
|
4月前
|
数据采集 数据可视化 数据挖掘
用 Excel+Power Query 做电商数据分析:从 “每天加班整理数据” 到 “一键生成报表” 的配置教程
在电商运营中,数据是增长的关键驱动力。然而,传统的手工数据处理方式效率低下,耗费大量时间且易出错。本文介绍如何利用 Excel 中的 Power Query 工具,自动化完成电商数据的采集、清洗与分析,大幅提升数据处理效率。通过某美妆电商的实战案例,详细拆解从多平台数据整合到可视化报表生成的全流程,帮助电商从业者摆脱繁琐操作,聚焦业务增长,实现数据驱动的高效运营。
|
6月前
|
存储 安全 大数据
网安工程师必看!AiPy解决fscan扫描数据整理难题—多种信息快速分拣+Excel结构化存储方案
作为一名安全测试工程师,分析fscan扫描结果曾是繁琐的手动活:从海量日志中提取开放端口、漏洞信息和主机数据,耗时又易错。但现在,借助AiPy开发的GUI解析工具,只需喝杯奶茶的时间,即可将[PORT]、[SERVICE]、[VULN]、[HOST]等关键信息智能分类,并生成三份清晰的Excel报表。告别手动整理,大幅提升效率!在安全行业,工具党正碾压手动党。掌握AiPy,把时间留给真正的攻防实战!官网链接:https://www.aipyaipy.com,解锁更多用法!
|
4月前
|
Python
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
11月前
|
数据采集 数据可视化 数据挖掘
利用Python自动化处理Excel数据:从基础到进阶####
本文旨在为读者提供一个全面的指南,通过Python编程语言实现Excel数据的自动化处理。无论你是初学者还是有经验的开发者,本文都将帮助你掌握Pandas和openpyxl这两个强大的库,从而提升数据处理的效率和准确性。我们将从环境设置开始,逐步深入到数据读取、清洗、分析和可视化等各个环节,最终实现一个实际的自动化项目案例。 ####
2031 10
|
4月前
|
Python
将Excel特定某列数据删除
将Excel特定某列数据删除
|
5月前
|
Java 测试技术 数据库
spring号码归属地批量查询,批量查询号码归属地,在线工具,可按省份城市运营商号段分类分开分别导出excel表格
简介:文章探讨Spring Boot项目启动优化策略,通过自定义监听器、异步初始化及分库分表加载优化等手段,将项目启动时间从280秒缩短至159秒,提升约50%,显著提高开发效率。
|
9月前
|
分布式计算 Hadoop 大数据
从Excel到Hadoop:数据规模的进化之路
从Excel到Hadoop:数据规模的进化之路
206 10
|
11月前
|
存储 Java easyexcel
招行面试:100万级别数据的Excel,如何秒级导入到数据库?
本文由40岁老架构师尼恩撰写,分享了应对招商银行Java后端面试绝命12题的经验。文章详细介绍了如何通过系统化准备,在面试中展示强大的技术实力。针对百万级数据的Excel导入难题,尼恩推荐使用阿里巴巴开源的EasyExcel框架,并结合高性能分片读取、Disruptor队列缓冲和高并发批量写入的架构方案,实现高效的数据处理。此外,文章还提供了完整的代码示例和配置说明,帮助读者快速掌握相关技能。建议读者参考《尼恩Java面试宝典PDF》进行系统化刷题,提升面试竞争力。关注公众号【技术自由圈】可获取更多技术资源和指导。
|
数据处理 Python
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。
602 3
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档