C# – Getting Error while Exporting GridView To Excel in .xlsx format

asp.netaspxgridviewcexcel-2010export-to-excel

I want to export GridView to excel(in .xlsx format).
Here is my code

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
 GridView gv;

protected void Button1_Click(object sender, EventArgs e)
{
    setGridView();
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    string fileName = "TestExcelFile.xlsx";
    Response.Buffer = true;
    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    //Response.ContentType = "application/vnd.ms-excel"; // Works perfectly for .xls files
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gv.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

private void setGridView()
{
    gv = new GridView();
    Queue q = new Queue();
    for (int i = 0; i < 20; i++)
    {
        q.Enqueue(i);
    }
    gv.DataSource = q;
    gv.DataBind();
 }
}

If I keep response content type as : Response.ContentType = "application/vnd.ms-excel"; then it works perfectly for excel's .xls format.

But for the excel file to be in .xlsx format, content type should be : Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";.

I can use .xls format but the problem is .xls format can hold only 64000 records and as per my project requirement I will get nearly 100000 (100K) rows. So I have to export it to an excel with .xlsx format to hold records above 64000.

Here is the error Text & Image:
"Excel cannot open the file 'TestExcelFile[2].xlsx' because the file format for the file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
Error while opening the exported Excel File

Best Answer

First of all, I have no idea what a "Lakh" is, but I guess it's more than 65535, but as far as I know the ASP.NET Gridview can't export it to XLSX format directly since it outputs it as raw HTML.

I'd recommend that you have a look at some component like EPPlus (http://epplus.codeplex.com/) which is much more flexible and scalable to work with for your requirements.

What you can do, as a workaround, though this won't be as elegant, would be to try the following code:

protected void btnExportData_Click(object sender, EventArgs e)
{
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;filename=output.xlsx");
    Response.Charset = "";
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    System.IO.StringWriter sw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);

    foreach (GridViewRow row in gvData.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
            for (int idxColumn = 0; idxColumn < row.Cells.Count; idxColumn++)
                row.Cells[idxColumn].Attributes.Add("class", "xlText");
    }

    gvData.RenderControl(htmlWriter);

    string appendStyle = @"<style> .xlText { mso-number-format:\@; } </style> ";
    Response.Write(appendStyle);

    Response.Write(sw.ToString());
    Response.End();
}

I've used that one Before for Excel 2007, but it's a hack and not very elegant.

Related Topic