简体   繁体   中英

Asp.net gridview export to excel formatting issue

I have created a simple application while will export data into excel. Now the data is exported to excel successfully but it will show an exception of formatting when I opened the downloaded excel.

public ActionResult ExportOrder()
            {
                List<OrderItem> data = new List<OrderItem>();            

                GridView gv = new GridView();
                gv.DataSource = data;
                gv.DataBind();
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=" + Common.GenerateSerialNo() + ".xls");
                Response.ContentType = "application/ms-excel";
                Response.Charset = "";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                gv.RenderControl(htw);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();

                return RedirectToAction("OrderProducts");
            }

This is my formatting issue while opening in Excel. Format Issue Image

Please suggest me to solve this issue.

I tried but found solutions to use NPOI or other Paid Tools. Can we solve the formatting issue without using any third party tool. I also tried some solutions but it didn't work for me.

You need to set the style on data bound not when doing the export as follows

private void gvPrint_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) {
        e.Row.Cells(0).Attributes.Add("class", "text");
        e.Row.Cells(1).Attributes.Add("class", "text");
        e.Row.Cells(2).Attributes.Add("class", "text");
        e.Row.Cells(6).Attributes.Add("class", "text");
        e.Row.Cells(7).Attributes.Add("class", "text");
        e.Row.Cells(8).Attributes.Add("class", "text");
    }
}

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