在VS2005中 GridView导入Excel的两点小技巧-附源码

 VS2005中 GridView导入Excel的导入需要注意的几点

最近带的项目遇到GridView导入Excel问题,总结出几点:

1、如果出现下面的错误提示可用重载VerifyRenderingInServerForm方法解决。

错误提示:
类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内

在后台文件中重载VerifyRenderingInServerForm方法,如:
public override void VerifyRenderingInServerForm(Control control)
{
     //base.VerifyRenderingInServerForm(control);
}

2、如果设置为 GetEncoding("GB2312"),导出的文件将会出现乱码。

可用Response.ContentEncoding = System.Text.Encoding.UTF7;
或者Encoding.UTF8等来解决,不过导入格式和字体上个人感觉UTF7比UTF8效果好些;
因人而异了:)

源码下载地址:http://bbs.52happy.net/read.php?tid=219811

相关代码如下:

Web.config配置:

<?xml version="1.0"?>
<!-- 
    注意: 除了手动编辑此文件以外,您还可以使用 
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
     “网站”->“Asp.Net 配置”选项。
    设置和注释的完整列表在 
    machine.config.comments 中,该文件通常位于 
    \Windows\Microsoft.Net\Framework\v2.x\Config 中
-->
<configuration>
    
<appSettings>
        
<!--数据库连接串-->
        
<add key="ConnectionString" value="data source=.;initial catalog=Northwind;user id=sa;password=sa;persist security info=true;packet size=4096"/>
    
</appSettings>
    
<connectionStrings/>
    
<system.web>
        
<!-- 
            设置 compilation debug="true" 将调试符号插入
            已编译的页面中。但由于这会 
            影响性能,因此只在开发过程中将此值 
            设置为 true。
        
-->
        
<compilation debug="true"/>
        
<!--
            通过 <authentication> 节可以配置 ASP.NET 使用的 
            安全身份验证模式,
            以标识传入的用户。 
        
-->
        
<authentication mode="Windows"/>
        
<!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 <customErrors> 节可以配置相应的处理步骤。具体说来,
            开发人员通过该节可以配置
            要显示的 html 错误页
            以代替错误堆栈跟踪。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        
-->
    
</system.web>
</configuration>

ASPX页面代码:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>无标题页</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
&nbsp;
        
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" OnPageIndexChanging="Paging">
        
</asp:GridView>
    
    
</div>
        
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="导出到Excel" />
    
</form>

</body>
</html>


实例代码:

/*
 *    // by XiaoYin [10/22/2006]
 
*/

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Xml;

public partial class _Default : System.Web.UI.Page 
{

    
/// <summary>
    
/// 链接字符串
    
/// </summary>

    public string ConnectString
    
{
        
get
        
{
            
return ConfigurationManager.AppSettings["ConnectionString"];
        }

    }


    
/// <summary>
    
/// 重载VerifyRenderingInServerForm方法
    
/// 确认在运行时为指定的 ASP.NET 服务器控件呈现 HtmlForm 控件。
    
/// </summary>
    
/// <param name="control">ASP.NET 服务器控件,它必须位于 HtmlForm 控件中</param>

    public override void VerifyRenderingInServerForm(Control control)
    
{
        
//base.VerifyRenderingInServerForm(control);
    }



    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!Page.IsPostBack)
        
{
            BindData();
        }

    }


    
/// <summary>
    
/// 绑定数据
    
/// </summary>

    public void BindData()
    
{
        
// 查询
        string query = "SELECT * FROM Categories";
        SqlConnection myConnection 
= new SqlConnection(ConnectString);
        SqlDataAdapter ad 
= new SqlDataAdapter(query, myConnection);
        DataSet ds 
= new DataSet();
        ad.Fill(ds, 
"Categories");
        GridView1.DataSource 
= ds;
        GridView1.DataBind();
    }


    
/// <summary>
    
/// 内存分页
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>

    protected void Paging(object sender, GridViewPageEventArgs e)
    
{
        GridView1.PageIndex 
= e.NewPageIndex;
        BindData();
    }


    
protected void Button1_Click(object sender, EventArgs e)
    
{
        Response.Clear();
        Response.Buffer 
= true;
        Response.Charset 
= "GB2312";
        Response.AppendHeader(
"Content-Disposition""attachment;filename=FileName.xls");
        
//gaoyang [10/21/2006] 经测试如果设置为 GetEncoding("GB2312"),导出的文件将会出现乱码。
        Response.ContentEncoding = System.Text.Encoding.UTF7;

        
//设置输出文件类型为excel文件。 
        Response.ContentType = "application/ms-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();
    }

}

posted @ 2006-10-22 10:39 ξ箫音ξ 阅读(7070) 评论(28)  编辑 收藏

  回复  引用  查看    
#1楼 2006-10-22 11:34 | 独孤雁      
收藏
  回复  引用  查看    
#2楼 2006-10-22 19:06 | 高海东      
这个导出的功能我可能后面也需要 谢谢
  回复  引用  查看    
#3楼 2006-10-22 22:14 | MK2      
这种方法还是以前DataGrid的方法`````就是不知道怎么将字体设置成“宋体”。。。。。。
  回复  引用  查看    
#4楼 2006-10-23 08:31 | 壮志      

  回复  引用    
#5楼 2006-10-23 16:30 | 嘿嘿 [未注册用户]
过来踩萧,嘿嘿。
using System.Drawing;
using NickLee.Common.ExcelLite;
代码部分
ExcelFile excelFile = new ExcelFile();
ExcelWorksheetCollection worksheets = excelFile.Worksheets;
ExcelWorksheet ws = excelFile.Worksheets.Add(HG1.ID);
StylesSample(excelFile.Worksheets.Add("中文样式"));
for(int i=0;i<HG1.Items.Count;i++)
{
for (int y = 0; y < HG1.Items[i].Cells.Count; y++)
{
ws.Cells[i+1, y].Value = HG1.Items[i].Cells[y].Text;

CellStyle tmpStyle = new CellStyle();
//跳转到下一行
//如果使用Rows.Height,请关闭页面的WrapText = false;
tmpStyle.WrapText = false ;
//这里设置背景色
tmpStyle.FillPattern.SetSolid(Color.Chocolate);
//字体颜色
tmpStyle.Font.Color = Color.White;
//是否是加粗
tmpStyle.Font.Weight = ExcelFont.BoldWeight;
//位置
tmpStyle.HorizontalAlignment = HorizontalAlignmentStyle.Center;
tmpStyle.VerticalAlignment = VerticalAlignmentStyle.Center;
ws.Cells[i + 1, y].Style = tmpStyle;
//制定数字转换
if (y == 4)
{
if (HG1.Items[i].Cells[y].Text.ToString() != "&nbsp;")
{
ws.Cells[i + 1, y].Value = Convert.ToDecimal(HG1.Items[i].Cells[y].Text.ToString());
//这里格式化为数字
ws.Cells[i + 1, y].Style.NumberFormat = "#.####";
}
else
{
//如果为数字,直接就转化为数字
//ws.Cells[i, y].Value = 0.0000F;
ws.Cells[i + 1, y].Value = 0;
}
}
//制定日期
if (y == 6)
{
if (HG1.Items[i].Cells[y].Text.ToString() != "&nbsp;")
{
ws.Cells[i + 1, y].Value = Convert.ToDateTime(HG1.Items[i].Cells[y].Text.ToString());
//这里格式化为数字
//ws.Cells[i + 1, y].Style.NumberFormat = "dddd, mmmm dd, yyyy";
ws.Cells[i + 1, y].Style.NumberFormat = "mm/dd/yyyy";
}
else
{
//如果为数字,直接就转化为数字
//ws.Cells[i, y].Value = 0.0000F;
ws.Cells[i + 1, y].Value = System.DateTime.Now;
//ws.Cells[i + 1, y].Style.NumberFormat = "dddd, mmmm dd, yyyy";
//ws.Cells[i + 1, y].Style.NumberFormat = "mm/dd/yyyy";
}
}
}
}
string fileName = Server.MapPath("../") + "\\file\\" + HG1.ID+".xls";

excelFile.SaveXls(fileName);

TryToDisplayGeneratedFile(fileName);
  回复  引用    
#6楼 2006-10-23 16:30 | xinxin[匿名] [未注册用户]
ad.Fill(ds, "Categories"); ConnectionString 属性尚未初始化。 怎么回事啊?我的字符串连接是用SqlDataSource做的,自动生成的
  回复  引用    
#7楼 2006-10-23 23:01 | sun2000sun [未注册用户]
可否给个箫心论坛的邀请码?谢谢!ss2000@163.com
  回复  引用    
#8楼 2006-10-24 12:40 | 77 [未注册用户]
代码下不了,注册也不行!!!!!!!!!!!!!!!!!
  回复  引用    
#9楼 2006-12-30 11:57 | 箱子 [未注册用户]
怎么能让他导出到Excel时,不弹出是否打开或保存的对话框,而是直接打开Excel文件???
  回复  引用  查看    
#10楼 2008-01-20 23:28 | coolxlc      
这个功能我也做过
但是只能用Excel2003打开不是乱码
用2005打开就是乱码
  回复  引用    
#11楼 2008-04-03 09:23 | 梁朋 [未注册用户]
VerifyRenderingInServerForm 没有找到适合的方法来重写!!
急急急啊!为什么???
谁知道,qq告诉我,谢谢了!
  回复  引用    
#12楼 2008-04-03 09:24 | 梁朋 [未注册用户]
VerifyRenderingInServerForm 没有找到适合的方法来重写!!
急急急啊!为什么???
谁知道,qq 406398723 告诉我,谢谢了
  回复  引用    
#13楼 2008-04-22 12:02 | yueshide [未注册用户]
好像翻页的有问题
this.GridView1.RenderControl(oHtmlTextWriter);报错
  回复  引用    
#14楼 2008-04-29 17:29 | 匿名 [未注册用户]
听一前辈说好像Excel导入到GridView内后 不能分页.
不知道是不是?

  回复  引用    
#15楼 2008-07-26 17:11 | zzg [未注册用户]
当用GridView导出Execl的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示。
有两种方法可以解决以上问题:
1.修改web.config(不推荐)<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"

CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>



标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2006-10-22 18:03 编辑过


相关链接: