将GridView导出到Excel

时间:2012-11-06 21:06:23

标签: c# asp.net excel gridview

我正在尝试将GridView导出为2010 Excel文件.xlsx格式。它适用于.xls我想知道是否有人可以帮助我。以下是我到目前为止的情况:

protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
        "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.DataBind();

        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");

        GridView1.HeaderRow.Cells[0].Style.Add("background-color", "#D1EEEE");

        GridView1.HeaderRow.Cells[1].Style.Add("background-color", "#D1EEEE");

        GridView1.HeaderRow.Cells[2].Style.Add("background-color", "#D1EEEE");

        GridView1.HeaderRow.Cells[3].Style.Add("background-color", "#D1EEEE");
        GridView1.HeaderRow.Cells[4].Style.Add("background-color", "#D1EEEE");
        GridView1.HeaderRow.Cells[5].Style.Add("background-color", "#D1EEEE");
        GridView1.HeaderRow.Cells[6].Style.Add("background-color", "#D1EEEE");
        GridView1.HeaderRow.Cells[7].Style.Add("background-color", "#D1EEEE");
        GridView1.HeaderRow.Cells[8].Style.Add("background-color", "#D1EEEE");
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {

            GridViewRow row = GridView1.Rows[i];
            row.BackColor = System.Drawing.Color.White;
            row.Attributes.Add("class", "textmode");
            if (i % 2 != 0)
            {

                row.Cells[0].Style.Add("background-color", "#FFFFFF");
                row.Cells[1].Style.Add("background-color", "#FFFFFF");
                row.Cells[2].Style.Add("background-color", "#FFFFFF");
                row.Cells[3].Style.Add("background-color", "#FFFFFF");

            }
        }
        GridView1.RenderControl(hw);
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

    }

2 个答案:

答案 0 :(得分:1)

见下文,它使用九种方法将数据导出到asp.net上的excel,它必须有所帮助:

9 Solutions to Export Data to Excel for ASP.NET

答案 1 :(得分:0)

请执行以下操作:

[HttpHead]
[HttpGet]
[ResponseType(typeof(string))]
public HttpResponseMessage LiveCheck(HttpRequestMessage request)
{
    HttpResponseMessage response;

    response =  request.CreateResponse(HttpStatusCode.OK);
    if (request.Method == HttpMethod.Get)
    {
        response.Content = new StringContent("OK", System.Text.Encoding.UTF8, "text/plain");
    }
    return response;
}

并且这些链接逐步显示如何执行此操作:

http://www.aspsnippets.com/Articles/Solution-ASPNet-GridView-Export-to-Excel-The-file-you-are-trying-to-open-is-in-a-different-format-than-specified-by-the-file-extension.aspx