<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Gridview_download.aspx.cs" Inherits="Gridview_download" %><!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" >
<meta http-equiv="content-type" content="application/ms-excel; charset=UTF-8"/>
<head runat="server">
    <title>文件download之Excel出力</title>
    <script type="text/javascript" src='<%=ResolveUrl("~/js/lib/jquery.js") %>'></script>    <script type="text/javascript" language="javascript">
         // イメージを変更する
       function changeImage(id)
       {   
           if(document.getElementById(id).getAttribute("src",2) == "../Resource/1.png")
           {
           document.getElementById(id).src = "../Resource/0.png";
           $('#'+id + " ~ input").val("0");        
           }
           else
           {
           document.getElementById(id).src = "../Resource/1.png";
           $('#'+id + " ~ input").val("1");
           }
      }
        function setHeader()
         {
            var t = document.getElementById("<%=GridView1.ClientID%>");
            var t2 = t.cloneNode(true);
            for(i = t2.rows.length -1;i > 0;i--){
              t2.deleteRow(i); 
            } 
            t.deleteRow(0); 
            t2.style.width="377px";
            t2.rows[0].cells[2].style.width="137px";
            document.getElementById("div_head").appendChild(t2);
         }    </script></head>
<body>
    <form id="form1" runat="server">
        <div style="height: 310px; width: 400; position: relative; left: 0px; top: 0px;">
            &nbsp;&nbsp;&nbsp;&nbsp;
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="一览下载" /><br />
            <br />
            <div id="div_head" style="width: 377;">
            </div>
            <div id="div_info" style="overflow-y: scroll; height: 180px; width: 381px;">
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="360px"
                    BackColor="White" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px"
                    CellPadding="0" ForeColor="Black" GridLines="Vertical">
                    <Columns>
                        <asp:BoundField DataField="NAME" HeaderText="姓名">
                            <HeaderStyle HorizontalAlign="Center" Height="40px" Width="120px" />
                            <ItemStyle HorizontalAlign="Center" Height="35px" Width="120px" />
                        </asp:BoundField>
                        <asp:BoundField HeaderText="团队编号" DataField="TEAM">
                            <HeaderStyle HorizontalAlign="Center" Height="40px" Width="120px" />
                            <ItemStyle HorizontalAlign="Center" Height="35px" Width="120px" />
                        </asp:BoundField>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                &nbsp;所属团队
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:Image ID="Image1" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"TEAM").ToString() == "1"?"~/Resource/1.png":"~/Resource/0.png" %>'
                                    onclick="changeImage(this.id);" Style="cursor: pointer; border-bottom: solid 1px black;
                                    padding-bottom: 2px;" />
                                <asp:HiddenField ID="HiddenField1" runat="server" />
                            </ItemTemplate>
                            <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Height="40px" Width="120px" />
                            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Height="35px" Width="120px" />
                        </asp:TemplateField>
                    </Columns>
                    <HeaderStyle BackColor="LightGray" Height="40px" Font-Bold="True" ForeColor="Black" />
                    <RowStyle BackColor="#CDE4EA" />
                    <FooterStyle BackColor="#CCCC99" />
                    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
                    <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
                    <AlternatingRowStyle BackColor="White" />
                </asp:GridView>
            </div>
        </div>
    </form>
</body>
</html>

解决方案 »

  1.   

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    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.Text;
    using System.IO;public partial class Gridview_download : System.Web.UI.Page
    {
        private DataTable CreateDataSource()
        {        DataTable dt = new DataTable();
            dt.Columns.Add("NAME", typeof(string));
            dt.Columns.Add("CODE", typeof(string));
            dt.Columns.Add("TEAM", typeof(string));
            DataRow row = dt.NewRow();
            row["NAME"] = "王一";
            row["CODE"] = "001";
            row["TEAM"] = "1";
            dt.Rows.Add(row);        row = dt.NewRow();
            row["NAME"] = "王五";
            row["CODE"] = "002";
            row["TEAM"] = "0";
            dt.Rows.Add(row);        row = dt.NewRow();
            row["NAME"] = "王帆";
            row["CODE"] = "003";
            row["TEAM"] = "1";
            dt.Rows.Add(row);        row = dt.NewRow();
            row["NAME"] = "李儲";
            row["CODE"] = "004";
            row["TEAM"] = "0";
            dt.Rows.Add(row);        row = dt.NewRow();
            row["NAME"] = "徐恋";
            row["CODE"] = "005";
            row["TEAM"] = "1";
            dt.Rows.Add(row);
            GridView1.DataSource = dt;
            Session["dtCopy"] = dt;
            return dt;
        }
        protected void Page_Load(object sender, EventArgs e)
        {        if (!IsPostBack)
            {
                GridView1.Attributes.Add("style", "table-layout:fixed");
                GridView1.DataSource = CreateDataSource();
                GridView1.DataBind();
                ClientScript.RegisterStartupScript(this.GetType(), "message", "<script language='javascript'>setHeader();</script>");
            }
        }    protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                StringWriter sw = new StringWriter(sb);
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                Page page = new Page();
                HtmlForm form = new HtmlForm();
                GridView1.EnableViewState = false;
                page.EnableEventValidation = false;
                page.DesignerInitialize();
                page.Controls.Add(form);
                // Sessionからデータを取得する
                DataTable dtGridview = (DataTable)Session.Contents["dtCopy"];            //データセットを初期化する
                DataSet ds = new DataSet();
                //データテーブルを初期化する
                DataTable dt = new DataTable();
                //データテーブルのカラムを設定する
                dt.Columns.Add("名前");            dt.Columns.Add("TEAMCODE");
                dt.Columns.Add("TEAMMARK");            //データテーブルの値を設定する
                for (int i = 0; i < dtGridview.Rows.Count; i++)
                {
                    dt.Rows.InsertAt(dt.NewRow(), i);
                    DataRow dr = dt.Rows[i];                dr["名前"] = dtGridview.Rows[i][0];
                    dr["TEAMCODE"] = dtGridview.Rows[i][2];                //デジタルが1の場合○を設定する
                    if ( Convert .ToInt32(dtGridview.Rows[i][2]) == 1)
                    {
                        dr["TEAMMARK"] = "○";
                    }
                    //デジタルが1の場合×を設定する
                    else
                    {
                        dr["TEAMMARK"] = "×";
                    }
                  
                }
                GridView gv = new GridView();
                ds.Tables.Add(dt);
                gv.DataSource = ds;
                gv.DataBind();            //ヘッドの顔色を設定する
                for (int j = 0; j < 3; j++)
                {
                    gv.HeaderRow.Cells[j].Attributes.Add("style", "background-color:#93CCDD");
                }
                //セルの書式を設定する
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    gv.Rows[i].Cells[0].Attributes.Add("style", "text-align:center");
                    gv.Rows[i].Cells[1].Attributes.Add("style", "text-align:center");
                    gv.Rows[i].Cells[2].Attributes.Add("style", "text-align:center");            }            DateTime DtTime = DateTime.Now;
                //システム時間を取得する
                string strTime = string.Format("{0:yyyyMMddHHmmss}", DtTime);            form.Controls.Add(gv);
                page.RenderControl(htw);
                Response.Clear();
                Response.Buffer = true;
                string strFileName = "文档一覧" + strTime + ".xls";
                string strEncodefileName = System.Web.HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8);
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", "attachment;filename = " + strEncodefileName);
                Response.Charset = "utf-8";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                Response.HeaderEncoding = System.Text.Encoding.UTF8;
                Response.Write(sb.ToString());
                Response.End();
            }
            catch
            {
            }
            finally
            {
            }
        }
    }
      

  2.   

    上面是完整的例子,只是没有图片文件,我想实现excel文件下载,功能基本实现,但是下载后是乱码。我这里用的都是日文环境,里面也没有汉字了,但仍然都是乱码,不知什么原因,希望各位能帮忙看看~~~
      

  3.   

    Response.Charset = "Shift_JIS";
    试试呢,不一定对啊。。
      

  4.   

    StringBuilder sb = new StringBuilder();
    sb.Append("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>");
     StringWriter sw = new StringWriter(sb);
      

  5.   

    试问LZ +   LS  ,若日语系统中,出力中文版的excel 怎么办?
    我现在的情况是,里面的内容都正常,就是在IE浏览器下出力的excel名字里面的 文字为乱码.
    有什么好办法解决么?