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

简介:

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

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

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

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

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

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

方法二:
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,如需转载请自行联系原作者

相关文章
|
28天前
|
关系型数据库 MySQL Shell
不通过navicat工具怎么把查询数据导出到excel表中
不通过navicat工具怎么把查询数据导出到excel表中
28 0
|
2天前
|
存储 Java
java的Excel导出,数组与业务字典匹配并去掉最后一个逗号
java的Excel导出,数组与业务字典匹配并去掉最后一个逗号
18 2
|
11天前
|
数据采集 存储 数据挖掘
使用Python读取Excel数据
本文介绍了如何使用Python的`pandas`库读取和操作Excel文件。首先,需要安装`pandas`和`openpyxl`库。接着,通过`read_excel`函数读取Excel数据,并展示了读取特定工作表、查看数据以及计算平均值等操作。此外,还介绍了选择特定列、筛选数据和数据清洗等常用操作。`pandas`是一个强大且易用的工具,适用于日常数据处理工作。
|
1月前
|
前端开发 JavaScript
使用Vue+xlsx+xlsx-style实现导出自定义样式的Excel文件
本文介绍了在Vue项目中使用`xlsx`和`xlsx-style`(或`xlsx-style-vite`)库实现导出具有自定义样式的Excel文件的方法,并提供了详细的示例代码和操作效果截图。
277 1
使用Vue+xlsx+xlsx-style实现导出自定义样式的Excel文件
|
1月前
|
前端开发 Python
使用Python+openpyxl实现导出自定义样式的Excel文件
本文介绍了如何使用Python的openpyxl库导出具有自定义样式的Excel文件,包括设置字体、对齐方式、行列宽高、边框和填充等样式,并提供了完整的示例代码和运行效果截图。
28 1
使用Python+openpyxl实现导出自定义样式的Excel文件
|
24天前
|
SQL JSON 关系型数据库
n种方式教你用python读写excel等数据文件
n种方式教你用python读写excel等数据文件
|
28天前
|
存储 Java Apache
|
1月前
|
SQL 分布式计算 DataWorks
DataWorks产品使用合集之如何直接导出excel文件
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
|
1月前
|
JavaScript 前端开发 easyexcel
基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程
本文展示了基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的完整过程,包括后端使用EasyExcel生成Excel文件流,前端通过Blob对象接收并触发下载的操作步骤和代码示例。
186 0
基于SpringBoot + EasyExcel + Vue + Blob实现导出Excel文件的前后端完整过程
|
1月前
|
数据可视化 Python
我是如何把python获取到的数据写入Excel的?
我是如何把python获取到的数据写入Excel的?
36 2