Lando Lando - 1 year ago 132
C# Question

Stop Date Auto-Format when Exporting from DataGrid to Excel in C#

I am currently formatting a Date for a specific Excel file Export from a DataSet/DataGrid.

The Date is formatted like so:

DateTime date = Convert.ToDateTime(entry.Date);
string formatdate = String.Format("{0:yyyy/MM/dd}", date);

Once creating the DataSet is said and done, I use the following code to Export the DataSet to an Excel file:

public static void ExportDStoExcel(DataSet ds, string filename)
HttpResponse response = HttpContext.Current.Response;
response.Charset = "";

response.ContentType = "application/";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

using (StringWriter sw = new StringWriter())
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];


My only problem is once I export this to Excel, Excel Auto-Formats the Dates like this: MM/DD/YYYY instead of YYYY/MM/DD.

I understand this could be achieved manually by opening in Excel, but the Export is being built into an Automated System and needs to be hard coded.

Is there any way of bypassing Excel's DateTime Auto-Formatting?

Answer Source

Right now you are just outputting HTML table, that Excel interprets how it likes. You'd have bring yourself down to Excel's level to be able to specify column's properties (set type to Text instead of General). This means that you need to generate actual xls file (there are various libraries out there for that). Or (if restriction to Office 2010 is acceptable) got with Open XML format which you can write with regular .NET API.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download