1

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

4
  • Please edit the code properly. Thanks Commented Jan 17, 2011 at 12:18
  • Can you open the sheet in Excel without any error? Is yes, please verify if there is any application (read) locking your file. Commented Jan 17, 2011 at 12:21
  • Make sure you're using "Microsoft Excel 12.0 Object library" COM component in project's reference. Commented Jan 17, 2011 at 12:25
  • yes i am using "Microsoft Excel 12.0 Object library" COM component in project's reference. but still the error is same Commented Jan 17, 2011 at 12:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.