简体   繁体   中英

exporting gridview to Ms Excel 2007

I am trying to export grid view data into excel 2007 ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM