日期:2014-05-17  浏览次数:20475 次

如何把GridView模板中的内容导入到Excel
本帖最后由 linjiangxian11 于 2012-08-09 20:33:47 编辑
    以下是把GridView的数据导入到Excel表的代码,有点特别的是,这个GridView中大量使用了模板。因此,必须先要判断模板的类型,再把模板的内容写到str字段里,最后写到Excel对应的Cell中。为了方便测试,我把模板都做成TextBox,可是每次运行到  if (GridView_Search.Controls[j].GetType() == typeof(TextBox))  这一句时,就会出现异常。

    我尝试把GridView_Search.Controls[j].GetType()改成GridView_Search.Columns[j].GetType(),但还是读取不到数据,我到底错在哪里了?请各位帮忙看看,谢谢!


-----------------------前台----------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table cellpadding="0" cellspacing="0" class="style1">
            <tr>
                <td>
                    <asp:Button ID="Button_SQLToExcel" runat="server" 
                        onclick="Button_SQLToExcel_Click" Text="导入到Excel表" /></td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="GridView_Search" runat="server" AutoGenerateColumns="False" 
                        CellPadding="0" DataSourceID="SqlDataSource1">
                        <Columns>
                            
                            <asp:TemplateField HeaderText="SupplierID" SortExpression="SupplierID">
                                <ItemTemplate>
 &