将Gridview数据导出到Excel - 更改标题名称

时间:2011-09-01 09:55:58

标签: asp.net vb.net

您是否有机会从gridview更改导出数据的标题名称。下面是我的代码,它的工作正常。我唯一的问题是我无法更改标题名称

我的代码

Dim strFilename As String = Now.Date.Month.ToString + Now.Date.Day.ToString + Now.Hour.ToString + Now.Minute.ToString + Now.Second.ToString

Response.AddHeader("content-disposition", "attachment;filename=" & strFilename & ".xls")
Response.Clear()
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"

Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
Dim dg As System.Web.UI.WebControls.DataGrid = New System.Web.UI.WebControls.DataGrid()

dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.End()

结果是

 ID  Fname
 1   aaa
 2   bbb
 2   ccc

我想要这样

Employee ID  First Name
1            aaa
2            bbb 
3            ccc

3 个答案:

答案 0 :(得分:0)

您尚未在GridView上定义任何列,因此它已自动生成它们,从而生成以下HTML(带有Excel标题):

<div>
    <table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
        <tr>
            <th scope="col">Employee ID</th><th scope="col">First Name</th>
        </tr>
        <tr>
            <td>1</td>
            <td>aaa</td>
        </tr>
        <tr>
            <td>2</td>
            <td>bbb</td>
        </tr>
        <tr>
            <td>3</td>
            <td>ccc</td>
        </tr>
    </table>
</div>

如果向GridView添加一些列,则可以实现所需的输出(不要忘记包含gv.AutoGenerateColumns = false):

    Response.AddHeader("content-disposition", "attachment;filename=tets.xls");
    Response.Clear();
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
    System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();

    BoundField column;

    column = new BoundField();
    column.DataField = "ID";
    column.HeaderText = "Employee ID";
    gv.Columns.Add(column);

    column = new BoundField();
    column.DataField = "FName";
    column.HeaderText = "First Name";
    gv.Columns.Add(column);

    gv.AutoGenerateColumns = false;
    gv.DataSource = Data.BuildData();
    gv.DataBind();
    gv.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();

答案 1 :(得分:0)

下面是我用来导出从here中删除的GridView的类。它可以处理模板列和图像控件(显示替代文本)。

您可能想要查看PrepareControlForExport()如何处理某些控件。您还可能需要在PrepareControlForExport()中添加更多控制器的处理,因为它并不完整。

public class ExportGridView
{
    public static void Export(String fileName, GridView gridView)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName));
        HttpContext.Current.Response.ContentType = "application/ms-excel";

        //  Create a table to contain the grid
        Table table = new Table();

        //  include the gridline settings
        table.GridLines = gridView.GridLines;

        //  add the header row to the table
        if (gridView.HeaderRow != null)
        {
            PrepareControlForExport(gridView.HeaderRow);
            table.Rows.Add(gridView.HeaderRow);
        }

        //  add each of the data rows to the table
        foreach (GridViewRow row in gridView.Rows)
        {
            PrepareControlForExport(row);
            table.Rows.Add(row);
        }

        //  add the footer row to the table
        if (gridView.FooterRow != null)
        {
            PrepareControlForExport(gridView.FooterRow);
            table.Rows.Add(gridView.FooterRow);
        }

        using (StringWriter stringWriter = new StringWriter())
        {
            using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
            {
                //  render the table into the htmlwriter
                table.RenderControl(htmlWriter);

                //  render the htmlwriter into the response
                HttpContext.Current.Response.Write(stringWriter.ToString());
                HttpContext.Current.Response.End();
            }
        }
    }

    private static void PrepareControlForExport(Control control)
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control c = control.Controls[i];

            if (c is LinkButton)
            {
                control.Controls.Remove(c);
                control.Controls.AddAt(i, new LiteralControl((c as LinkButton).Text));
            }
            else if (c is ImageButton)
            {
                control.Controls.Remove(c);
                control.Controls.AddAt(i, new LiteralControl((c as ImageButton).AlternateText));
            }
            else if (c is HyperLink)
            {
                control.Controls.Remove(c);
                control.Controls.AddAt(i, new LiteralControl((c as HyperLink).Text));
            }
            else if (c is Image)
            {
                control.Controls.Remove(c);
                control.Controls.AddAt(i, new LiteralControl((c as Image).AlternateText));
            }
            else if (c is DropDownList)
            {
                control.Controls.Remove(c);
                control.Controls.AddAt(i, new LiteralControl((c as DropDownList).SelectedItem.Text));
            }
            else if (c is CheckBox)
            {
                control.Controls.Remove(c);
                if ((c as CheckBox).Checked)
                {
                    control.Controls.AddAt(i, new LiteralControl("True"));
                }
                else
                {
                    control.Controls.AddAt(i, new LiteralControl("False"));
                }
            }
            else if (c is HiddenField)
            {
                control.Controls.Remove(c);
            }

            if (c.HasControls())
            {
                PrepareControlForExport(c);
            }
        }
    }
}

答案 2 :(得分:0)

这是我原来的DataGrid答案,只是为了完整起见......

您尚未在DataGrid上定义任何列,因此它已自动生成它们,从而产生以下HTML(带有Excel标题):

<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
    <tr>
        <td>ID</td><td>FName</td>
    </tr>
    <tr>
        <td>1</td><td>aaa</td>
    </tr>
    <tr>
        <td>2</td><td>bbb</td>
    </tr>
    <tr>
        <td>3</td><td>ccc</td>
    </tr>
</table>

如果向DataGrid添加一些列,则可以实现所需的输出(不要忘记包含dg.AutoGenerateColumns = false):

Response.AddHeader("content-disposition", "attachment;filename=tets.xls");
Response.Clear();
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();

BoundColumn column;

column = new BoundColumn();
column.DataField = "ID";
column.HeaderText = "Employee ID";
dg.Columns.Add(column);

column = new BoundColumn();
column.DataField = "FName";
column.HeaderText = "First Name";
dg.Columns.Add(column);

dg.AutoGenerateColumns = false;
dg.DataSource = Data.BuildData();
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();