1
votes

I am trying to export grid view data into excel 2007 i.e. xlsx format. but its giving error.

i am using following code

protected void Button1_Click(object sender, EventArgs e)

    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=text.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.DataSource = Presenter.CurrentModel.BillStatementGlModelRecords;
        GridView1.DataBind();
        GridView1.AllowPaging = false;

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

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;
            //Apply text style to each Row
            row.Attributes.Add("class", "textmode");
        }
        GridView1.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

but not working properly and on opening the file it gives following error "Excel cannot open the file 'ChangeRequestList[2].xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file"

Can anyone help me?

Thanks

1
Please edit the code properly. Thanks - Nayan
Can you open the sheet in Excel without any error? Is yes, please verify if there is any application (read) locking your file. - Nayan
Make sure you're using "Microsoft Excel 12.0 Object library" COM component in project's reference. - Nayan
yes i am using "Microsoft Excel 12.0 Object library" COM component in project's reference. but still the error is same - Sumit Gupta

1 Answers

1
votes

Have a look at this Code - I already used it and it's working. But it produces plain text (csv I guess) and not xlsx but I think that shouldn't be a problem though.