Domanda

I wish to export my datatable to excel.

I have a column which has values like 2/5 1/5 ... After export this data to excel it looks as 02.May 01.May (Date Format)

How can i export this column so that excel treats it like a string instead of converting it to a date.?

this is my ExportToExcel method

protected void ExportToExcel()
{

    DataTable dt = new DataTable();

    dt = Session["aaa"] as DataTable;

    if (dt.Rows.Count > 0)
    {
        string filename = "DownloadMobileNoExcel.xls";
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        DataGrid dgGrid = new DataGrid();
        dgGrid.DataSource = dt;
        dgGrid.DataBind();

        //Get the HTML for the control.
        dgGrid.RenderControl(hw);
        //Write the HTML back to the browser.
        //Response.ContentType = application/vnd.ms-excel;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
        this.EnableViewState = false;
        Response.Write(tw.ToString());
        Response.End();
    }
}

public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}
È stato utile?

Soluzione

One solution might be to loop through al the cells in your DataTable for the column that is causing the issue and prepend a single quote ' character before the current value.

In other words 2/5 would become '2/5. This should force Excel to treat the data as text.

Altri suggerimenti

before this line Response.Write(tw.ToString()); you have to put this line Response.Write("<head><style> td {mso-number-format:\\@;} </style></head><body>"); that's it

You can see below.

Response.Write("<head><style> td {mso-number-format:\\@;} </style></head><body>");
Response.Write(tw.ToString());

You can also see whole code, It looks like

protected void ImgExcel_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment; filename=AddGoodsDetails_" + DateTime.Now + ".xls");
    Response.ContentType = "application/vnd.xls";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    gvView_2.RenderControl(htmlWrite);
    Response.Write("<head><style> td {mso-number-format:\\@;} </style></head><body>");
    Response.Write(stringWrite.ToString());
    Response.End();
}

gvView_2 is an id of GridView, you can understand i hope this solution will help in your problem.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top