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

博客展示了使用C#代码实现Excel文件导出的功能。通过设置响应头、编码、内容类型等,将数据以Excel文件形式输出。代码中涉及DataGrid和GridView的渲染控制,同时提到编码设置不当可能导致文件乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前台代码:html
ExpandedBlockStart.gifContractedBlock.gif<%dot.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.gifusing 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.gifContractedBlock.gif
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// WebForm1 的摘要说明。
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class ExportExcel : System.Web.UI.Page
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.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.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// 在此处放置用户代码以初始化页面
InBlock.gif
            if(!IsPostBack)
InBlock.gif                BindData();
InBlock.gif            
InBlock.gif            
ExpandedSubBlockEnd.gif        }

InBlock.gif        
private void BindData()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.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.gifExpandedSubBlockStart.gif        
Web Form Designer generated code#region Web Form Designer generated code
InBlock.gif        
override protected void OnInit(EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//
InBlock.gif            
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
InBlock.gif            
//
InBlock.gif
            InitializeComponent();
InBlock.gif            
base.OnInit(e);
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
InBlock.gif        
/// 此方法的内容。
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private void InitializeComponent()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{    
InBlock.gif            
this.btnMIME.Click += new System.EventHandler(this.btnMIME_Click);
InBlock.gif            
this.Load += new System.EventHandler(this.Page_Load);
InBlock.gif
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
InBlock.gif        
private void btnMIME_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值