Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export dates to Csv and tell excel the format

My program (C# .Net 4.5) have to be able to generate some reports which can be loaded into Excel. I have choosen to export the reports as .csv format due to it being the most simple way to export to a format excel understands. And it does not requre Excel to be installed on the machine running my program.

My problem is exporting the dates.

My program is going to run on customer PC's which may (most likely) have different ways to show dates, which means excel expects dates in different formats.

My current solution is to export dates as:

DateTime LogTime = DateTime.Now;
String TimeFormat = //The format for the specific location, like: "HH:mm:ss dd/MM-yyyy"

//To csv:
// ="10:24:13 27-05-2014"
String reportTime = "=\""+LogTime.ToString(TimeFormat)+"\"";

The problem with this is i create different files based on different locations. So sending a file from one location to another may result in the date being wrong.

My question is, are there someway to tell Excel which format my date is in? Something like:

//To csv:
// =DateFormatted(10:24:13 27-05-2014,HH:mm:ss dd/MM-yyyy)
String reportTime = "=DateFormatted(" + LogTime.ToString(TimeFormat) + "," + TimeFormat + ")";

Then Excel know the exactly how to read the dates without I have to worry about different locations.

like image 364
Mr. Java Wolf Avatar asked May 30 '14 13:05

Mr. Java Wolf


People also ask

Why does my exported CSV data get converted to weird formats?

Instead, this is due to the way Excel and other spreadsheet programs open a CSV file and display the data therein. Basically, spreadsheet programs are designed to be used for calculation purposes, so they tend to apply mathematical formats to numbers when the CSV file is opened directly into the program.


3 Answers

Export the dates in the format yyyy-MM-dd HH:mm:ss

like image 184
Ciarán Avatar answered Oct 05 '22 13:10

Ciarán


As you are saving to CSV I'm afraid there isn't.

But you can use the yyyy/MM/dd hh:mm:ss format. As fas as I know this will work in all cultures.

like image 39
Stefano Altieri Avatar answered Oct 05 '22 12:10

Stefano Altieri


In my experience, the open-source NPOI libraries (https://npoi.codeplex.com/) are excellent for this.

  • You can export/import data to/from Excel, and Word for that matter
  • They do NOT require Excel to be installed on the machine
  • Support for both xls and xlsx formats
  • Complete control over formatting
  • Overall, way more functionality than would ever be possible with csv
like image 20
SlimsGhost Avatar answered Oct 05 '22 14:10

SlimsGhost