Stop Excel from automatically converting certain text values to dates
Asked Answered
T

36

627

Does anyone happen to know if there is a token I can add to my csv for a certain field so Excel doesn't try to convert it to a date?

I'm trying to write a .csv file from my application and one of the values happens to look enough like a date that Excel is automatically converting it from text to a date. I've tried putting all of my text fields (including the one that looks like a date) within double quotes, but that has no effect.

Thagard answered 2/10, 2008 at 23:30 Comment(9)
Yeah, like when a file with 10000 usernames has one such as "april25", that gets converted to a date, and eventually gets processed as "apr-25", resulting in a "username not found" error, because you didn't expect Excel to be converting a single value to a date, 4000 records into the file, while leaving the rest text. What lame CSV reading code; really, isn't it supposed to guess the type based on the first X records and stick with it? Or leave it all text. If I want it formatted as "general", I can pick that later. By assuming "general" right from the start, it risks text data corruption.Woodbine
I had the issue when doing copy and paste. For all searching the solution, select the target column, set it to a string/text format, then copy source and do a special paste (right-click) with 'values only'. Preserves values, no date formatting.Cannon
I just want to add that I consider this behavior of Excel to be a serious flaw. What about all the people that don't have the luxury to change the contents of the csv file prior to importing to Excel? Or what about people who don't realize this problem until after making lots of other changes to the CSV file? It makes working with CSV files in Excel a mess.Mucous
Are you using DatatableJS? Because I already know how to do this with that API. If you need this you can found it here : https://mcmap.net/q/65271/-datatables-tabletools-format-data-as-text-when-exporting-to-excelFunerary
@robguinness: What would be great is if there were a table-based data format that's almost as simple to generate and parse as CSV, but with type-specific literals. Where 1234 is an integer and @2000-04-25@ is a date, but "1234" and "april25" are unambiguously text strings.Crosshead
All these solutions to use File -> Open -> Import work ok for us because we know what we're doing, but it is useless for the other 99.5% of the world who don't understand navigating the filesystem from /within/ an application. They see a file, to use it they double-click on it. I've spent 25 years teaching people how to use office applications and writing code that generates data for said office applications, and using the /application/ to look for the file to use is completely beyond almost everybody.Ellett
It is deeply deeply ingrained that you use the /filer/ to look for the file you want to use, then 'launch' the /file/. Even those people who I can teach to drag'n'drop can't get it. It's difficult to believe, it's like wondering how somebody can not understand how to turn a TV on by pressing a button on the remote control.Ellett
If anyone is wondering exactly when this issue occurs, here are my observations. 1. 10 is safe for integers, 11 is converted to scientific notation 2. 15-n decimal places are kept the rest are thrown out, where n is the number of digits left of the decimal point. For example, if 2 digits are to the left of the decimal point then 13 digits are kept to the right of it 3. Behavior 1 and 2 is consistent regardless of the column location of the value. I.e. it can be at the beginning, end or middle of a series of columns.Bastia
I came across this issue too. It's safe to say excel is not made for developers. I'm looking for alternatives.Alodi
G
400

I have found that putting an '=' before the double quotes will accomplish what you want. It forces the data to be text.

eg. ="2008-10-03",="more text"

EDIT (according to other posts): because of the Excel 2007 bug noted by Jeffiekins one should use the solution proposed by Andrew: "=""2008-10-03"""

Gunstock answered 2/10, 2008 at 23:33 Comment(15)
I'm accepting this answer because 1) my csv file will only be used by Excel, and 2) this is for accounting and can't have a ' at the beginning, and 3) I don't want them to have to do an import. I just want them to open the csv.Thagard
Great! But because of the Excel 2007 bug use the solution proposed by Andrew: "=""2008-10-03""". Updated the post.Matter
This doesn't work for me in Excel 2010 if the text is too long :(Previous
I ended up prefacing my text with a | symbol (which still shows up in Excel). It is less than optimal but since the excel documents I'm generating are mainly just for reading data, this works in my case.Previous
The reason this works is because when Excel sees the character "=" it decides to evaluate the expression following it. In this case the expression is simply a string literal and the value of a string literal is the content of the string. Thus the quotation marks magically disappear. You can put =1+2+3 and get the value 6 after CSV import. The formula itself is not destroyed in the import process.Bryan
If you use ="sometext" solution(formula trick) then you should know that Excel (tested with 2010) has limit of 255 chars for expressions inside formulas. This means that anything after 255 chars will be chopped off by our beloved Excel.Myranda
This answer just saved my life. All the workarounds include "import this, pre-format the cells, etc." I just wanted to double click the .csv file and this solution is it! Thanks a lot, my friend.Deirdra
Why 6 double quotes? not 4?Nightspot
There is a big problem with this approach - if you open the file in excel and edit and then save and open again all these " disappearClaqueur
Where do I donate for @Jarod Elliott?Outherod
this fix also works for Numbers on MAC. Awesome Find.Xylography
Does this issue still affect newer versions of Excel like Excel 2019, Excel 2016, Excel 2013 or Excel 2010?Bladdernose
In my case excel was parsing "4/5" as a date, and I managed to get around that by adding a space at the beginning " 4/5" ... This at least doesn't break other csv parsers, but it might not work with all date formatsComprehension
Its crazy that in this day and age, we can't just tell Excel NOT to change date formats. The amount of grief this has caused me with my CSV file is bonkers. Having to use a dirty work around like ="xxx" shouldn't be a solution. Its a hack at best, but M$ should pull their fingers out and actually FIX their software :(Napiform
This hacky hack doesn't work with Libreoffice, so the CSV file looses portability. LO imports the ="text" literally, without the outer delimiters.Telescopy
T
183

I know this is an old question, but the problem is not going away soon. CSV files are easy to generate from most programming languages, rather small, human-readable in a crunch with a plain text editor, and ubiquitous.

The problem is not only with dates in text fields, but anything numeric also gets converted from text to numbers. A couple of examples where this is problematic:

  • ZIP/postal codes
  • telephone numbers
  • government ID numbers

which sometimes can start with one or more zeroes (0), which get thrown away when converted to numeric. Or the value contains characters that can be confused with mathematical operators (as in dates: /, -).

Two cases that I can think of that the "prepending =" solution, as mentioned previously, might not be ideal is

  • where the file might be imported into a program other than MS Excel (MS Word's Mail Merge function comes to mind),
  • where human-readability might be important.

My hack to work around this

If one pre/appends a non-numeric and/or non-date character in the value, the value will be recognized as text and not converted. A non-printing character would be good as it will not alter the displayed value. However, the plain old space character (\s, ASCII 32) doesn't work for this as it gets chopped off by Excel and then the value still gets converted. But there are various other printing and non-printing space characters that will work well. The easiest however is to append (add after) the simple tab character (\t, ASCII 9).

Benefits of this approach:

  • Available from keyboard or with an easy-to-remember ASCII code (9),
  • It doesn't bother the importation,
  • Normally does not bother Mail Merge results (depending on the template layout - but normally it just adds a wide space at the end of a line). (If this is however a problem, look at other characters e.g. the zero-width space (ZWSP, Unicode U+200B)
  • is not a big hindrance when viewing the CSV in Notepad (etc),
  • and could be removed by find/replace in Excel (or Notepad etc).
  • You don't need to import the CSV, but can simply double-click to open the CSV in Excel.

If there's a reason you don't want to use the tab, look in an Unicode table for something else suitable.

Another option

might be to generate XML files, for which a certain format also is accepted for import by newer MS Excel versions, and which allows a lot more options similar to .XLS format, but I don't have experience with this.

So there are various options. Depending on your requirements/application, one might be better than another.


Addition

It needs to be said that newer versions (2013+) of MS Excel don't open the CSV in spreadsheet format any more - one more speedbump in one's workflow making Excel less useful... At least, instructions exist for getting around it. See e.g. this Stackoverflow: How to correctly display .csv files within Excel 2013? .

Tobe answered 27/2, 2013 at 8:16 Comment(13)
I got correct leading zeroes after adding \t to my separation character ; ... damn you MS Office, why did this have to take me more than 2 minutes to figure out?Spitball
Adding \t at the end of all values does indeed the trick. It's a hacky workaround, but in practice it works fine. I prefer this to the formula trick with the equal '=', because the former might be difficult to work with in other tools.Marcelinomarcell
There are not enough upvotes that can express my gratitude for you. Search and replace in notepad++ ',' to '\t,\t' (to accommodate for first and last columns as well) works like a charm. Thanks.Claudieclaudina
In my MySQL query (for CSV output through PHP), I used CONCAT('\t', column_name). Also did the trick. Thanks!Olfactory
CSV's are not small and easy to generate when working on files with almost a million rows. Just say'n... For CSV files I wish Microsoft would just get off their a$$ and fix this. They shouldn't try to assume what we want, and should at least ask before applying a format other than text for a known text file type. Or, at the bare minimum give us the original value back if you change the format back to text. I mean, isn't that the logical approach? But thank you for your answer, it helped.Amylopectin
This works great if you intend to keep the data in Excel but I find that if I copy data from the excel sheet and paste into notepad it shows up as " 1234"Haemostat
Yes @zisha, as mentioned in the 5th bullet point, if that bothers you, you should do a find/replace on the file. It's a hack and not everything works transparently - one needs to use it intelligently depending on circumstances.Tobe
Great idea. Alas, Numbers is a bit "smarter" than Excel, and doesn't fall for the tab trick. Best alternative I can come up with is a leading ', since it's kinda well understood and not too distracting... but an invisible would be better.Antin
Note that prefixing \t will screw up the cursor position when trying to edit the cell. It will also add visible padding on the right (you'll see it if you right-slign the cell). An alternative is to use "\xA0" non-breaking-space. It will appear as a character of padding on the left, but won't interfere with editing. It will also persist through a save-to-CSV & reload.Patently
Oops... I just realized you're suggesting appending it, not prefixing it. That will stop Excel reinterpreting dates and dropping leading zeros, but it WON'T stop a string that starts with '-' or '+' or '@' or '=' from being interpreted as a formula (with potentially very bad consequences-- google "CSV injection"). For such cases, consider BOTH a space prepended at the start, and a tab or \xA0 character appended at the end...Patently
@Heath maybe a leading \xA0 would work for you? At least it's not a visible character...Patently
Thanks @Dion. I can't manage to reproduce the original issue with Numbers 6.1 any more (text refuses to auto-convert to a date!) but will keep that in mind if it crops up again.Antin
I keep wondering which version of future Excel would finally have a big simple button at the corner which disable all "smart" automatic conversionsInebriety
K
107

Working off of Jarod's solution and the issue brought up by Jeffiekins, you could modify

"May 16, 2011"

to

"=""May 16, 2011"""
Koslo answered 16/5, 2011 at 21:48 Comment(7)
Doesn't work in Excel 2010 if the text is longer than a certain length.Previous
@Andrew, This "fix" will cause problems if you need to have " values anywhere inbetween the date.Teresetereshkova
FYI, if you save the Excel file the = goes away and you're back to square one the next time you open in.Walls
My experience matches neither steve nor d512. It works for me in the incoming .csv in Excel 2013, and after saving as .xlsx it does not revert. Easy enough to for anyone to test using this row of data: "806676","None","41","=""May 16, 2011""","100.00","False"Macaroni
In Excel 2016 non of this appears to work through a save.Squire
@Macaroni Try "806676","None","41","=""05-16-2011""","100.00","False" instead and you will see a save and reload loses the hyphenated text.Squire
@Squire I see what you mean. All, FYI I just upvoted https://mcmap.net/q/64008/-stop-excel-from-automatically-converting-certain-text-values-to-dates (the trailing tab kludge). Also FYI, I am using Microsoft Office Professional Plus 2013.Macaroni
C
73

I had a similar problem and this is the workaround that helped me without having to edit the csv file contents:

If you have the flexibility to name the file something other than ".csv", you can name it with a ".txt" extension, such as "Myfile.txt" or "Myfile.csv.txt". Then when you open it in Excel (not by drag and drop, but using File->Open or the Most Recently Used files list), Excel will provide you with a "Text Import Wizard".

In the first page of the wizard, choose "Delimited" for the file type.

In the second page of the wizard choose "," as the delimiter and also choose the text qualifier if you have surrounded your values by quotes

In the third page, select every column individually and assign each the type "Text" instead of "General" to stop Excel from messing with your data.

Hope this helps you or someone with a similar problem!

Calvert answered 21/2, 2013 at 5:6 Comment(5)
Oh, by the way I am not the first to discover this. risingline.com/use-excel-read-csv-without-reformatting.php That web page also has the helpful instruction that you can shift-click the columns in the third page of the wizard to select them all together before assigning each the type "Text".Calvert
This may work for date values, but it doesn't seem to work for things excel interprets as numeric. If your string is all numbers and commas, "Text" format is going to be scientific number format.Condensation
this worked perfectly for me and didn't involve any changes to my file except to rename it as .txt. thank you.Macruran
Unfortunately, Excel only lets you do this for the first 6 columns. If you need more, a better approach is to copy the contents of the csv, create and empty excel file, select all columns/rows and set the type to Text, then paste the contents and use Data | Text to columnsPlanometer
This is the best solution and should be marked as the answer.Ovariectomy
P
41

2018

The only proper solution that worked for me (and also without modifying the CSV).

Excel 2010:

  1. Create new workbook
  2. Data > From Text > Select your CSV file
  3. In the popup, choose "Delimited" radio button, then click "Next >"
  4. Delimiters checkboxes: tick only "Comma" and uncheck the other options, then click "Next >"
  5. In the "Data preview", scroll to the far right, then hold shift and click on the last column (this will select all columns). Now in the "Column data format" select the radio button "Text", then click "Finish".

Excel office365: (client version)

  1. Create new workbook
  2. Data > From Text/CSV > Select your CSV file
  3. Data type detection > do not detect

Note: Excel office365 (web version), as I'm writing this, you will not be able to do that.

Pomander answered 12/8, 2018 at 7:59 Comment(4)
This works without changing the CSV files beforehand, so I think this should be the correct answer.Excruciating
This looks like the correct answer. I had high hopes. But on MacOS (office365), I cannot select ALL columns: there is no horizontal scroll in the preview window shown in the text import wizard, such that I can only select the visible columns. I tried short cuts (CMD+A, or other things), to no avail. The option "do not detect" does not exist either. I'm devastated.Schiro
Excel office 365, select File, Options, Data. There are check boxes to show the legacy data import wizards if needed.Electro
Correct answer or not, thank you, this is what most of us are really after. It was what I needed in 2023. Wish I had figured this out a few years ago.Intonate
E
29

WARNING: Excel '07 (at least) has a(nother) bug: if there's a comma in the contents of a field, it doesn't parse the ="field, contents" correctly, but rather puts everything after the comma into the following field, regardless of the quotation marks.

The only workaround I've found that works is to eliminate the = when the field contents include a comma.

This may mean that there are some fields that are impossible to represent exactly "right" in Excel, but by now I trust no-one is too surprised.

Edmead answered 10/12, 2010 at 19:58 Comment(6)
I just tested this in excel 2007, and it works correctly for me. However if there is a leading space before the quotes, then it does not parse comma correctly.Florella
This wouldn't appear to be a bug according to RFC 4180. The correct way to quote the field is to quote the whole field and then double quote internal quotes. So "=""field, content""" tools.ietf.org/html/rfc4180Kweisui
@PeterStephens, This doesn't work if field, content has "within it. E.g. "=""field, co""ntent"""Teresetereshkova
@Teresetereshkova Probably the embedded quote has to be double quoted, turning into """".Convolution
I can confirm @ErikE's suggestion is correct. For a field with value 1"2, if you choose to use this trick (as opposed to just leaving it be as "1""2" in the file - excel would already have treated is as text), then the final correct string in the Excel-targeting CSV file ends up being "=""1""""2""".Tangency
However, this trick breaks down after 255 characters of field length! If you really really need to do this, then you need to break up your longer-than-255-character values into multiple substrings, like "=CONCATENATE(""1""""2"",""3"")" for value 1"23. I can't seem to find a reliable way of targeting Excel that isn't absurd.Tangency
B
27

While creating the string to be written to my CSV file in C# I had to format it this way:

"=\"" + myVariable + "\""
Bid answered 21/4, 2014 at 13:9 Comment(3)
this woked for me in Rails also. ThanksAverett
Works on Java as WellAthlete
Worked for me in JavaScript using Papa Parse.Wilkerson
M
18

In Excel 2010 open a new sheet. On the Data ribbon click "Get External Data From Text". Select your CSV file then click "Open". Click "Next". Uncheck "Tab", place a check mark next to "Comma", then click "Next". Click anywhere on the first column. While holding the shift key drag the slider across until you can click in the last column, then release the shift key. Click the "text" radio button then click "Finish"

All columns will be imported as text, just as they were in the CSV file.

Madelyn answered 6/2, 2014 at 21:15 Comment(3)
I ran into a same problem, but following @Rob's instructions carefully would work perfect!. Thank youOlodort
The Data From Text assistant does unfortunately not support multi-line cells. If such a multi-line text is encountered, it will write all lines after the first into new rows, breaking the entire import. It only interprets the line breaks correctly if you open the CSV file by double clicking. Damn you Microsoft...Equality
Unfortunately this does not solve the issue of Excel's random formatting "help" - the text DEC1 is still changed to the date Dec-01. Same with text of YYYY-MM-DD being switched to DD/MM/YYYY. :(Mission
E
13

Still an issue in Microsoft Office 2016 release, rather disturbing for those of us working with gene names such as MARC1, MARCH1, SEPT1 etc. The solution I've found to be the most practical after generating a ".csv" file in R, that will then be opened/shared with Excel users:

  1. Open the CSV file as text (notepad)
  2. Copy it (ctrl+a, ctrl+c).
  3. Paste it in a new excel sheet -it will all paste in one column as long text strings.
  4. Choose/select this column.
  5. Go to Data- "Text to columns...", on the window opened choose "delimited" (next). Check that "comma" is marked (marking it will already show the separation of the data to columns below) (next), in this window you can choose the column you want and mark it as text (instead of general) (Finish).

HTH

Eisenach answered 30/11, 2015 at 17:35 Comment(4)
The manual effort was also unappealing to me. However, after exhausting every possibility at hand, this one was the most robust and reliable.Eisenach
Batch processing nonetheless.Eisenach
This is actually the best answer here that requires the least amount of work. I wish you could just set some option to force it to not parse the file.Holbrook
You can also replace all commas with tabs, then it will auto deliminateHolbrook
A
12

Here is the simple method we use at work here when generating the csv file in the first place, it does change the values a bit so it is not suitable in all applications:

Prepend a space to all values in the csv

This space will get stripped off by excel from numbers such as " 1"," 2.3" and " -2.9e4" but will remain on dates like " 01/10/1993" and booleans like " TRUE", stopping them being converted into excel's internal data types.

It also stops double quotes being zapped on read in, so a foolproof way of making text in a csv remain unchanged by excel EVEN IF is some text like "3.1415" is to surround it with double quotes AND prepend the whole string with a space, i.e. (using single quotes to show what you would type) ' "3.1415"'. Then in excel you always have the original string, except it is surrounded by double quotes and prepended by a space so you need to account for those in any formulas etc.

Aeriela answered 28/1, 2013 at 18:5 Comment(2)
This worked for me. I had some values like 1-1-1 that get auto converted to dates. As mentioned the space will transfer so the value is changed, but I do a strip on it when parsing so for me that isn't a big deal.Eshelman
Space no longer works to prevent date interpretation or stripping of leading zeros. But you can use a non-breaking-space "\xA0" instead - that will work.Patently
M
9

This is a only way I know how to accomplish this without messing inside the file itself. As usual with Excel, I learned this by beating my head on the desk for hours.

Change the .csv file extension to .txt; this will stop Excel from auto-converting the file when it's opened. Here's how I do it: open Excel to a blank worksheet, close the blank sheet, then File => Open and choose your file with the .txt extension. This forces Excel to open the "Text Import Wizard" where it'll ask you questions about how you want it to interpret the file. First you choose your delimiter (comma, tab, etc...), then (here's the important part) you choose a set columns of columns and select the formatting. If you want exactly what's in the file then choose "Text" and Excel will display just what's between the delimiters.

Maribeth answered 27/8, 2013 at 15:8 Comment(1)
This just worked fine for me on 2015-03-03 working with Excel for Mac 2011 (version 14.4.8 150116), working with the data in the SO question awk — avoid reformatting of date-like values, where the problem is with Excel rather than awk, despite the question title.Gavial
L
8

(Assuming Excel 2003...)

When using the Text-to-Columns Wizard has, in Step 3 you can dictate the data type for each of the columns. Click on the column in the preview and change the misbehaving column from "General" to "Text."

Lisabeth answered 2/10, 2008 at 23:34 Comment(2)
This is an excellent choice if I could force the user to use the import process.Thagard
This actually doesn't help the problem, as numbers in the TEXT column will be converted to NUMBERS when exporting to .csv anyways...Cristoforo
T
6

What I have done for this same problem was to add the following before each csv value: "=""" and one double quote after each CSV value, before opening the file in Excel. Take the following values for example:

012345,00198475

These should be altered before opening in Excel to:

"="""012345","="""00198475"

After you do this, every cell value appears as a formula in Excel and so won't be formatted as a number, date, etc. For example, a value of 012345 appears as:

="012345"
Trek answered 8/12, 2015 at 1:12 Comment(1)
The OP said there are values stored in text fields. In that case, storing them as a number would potentially change the value. Additionally, my example above is not a decimal that can be represented by 1234500198475E-8. It is two fields in a row of a CSV file. Field 1 is 012345 and field 2 is 00198475. Both are stored as strings with leading zeroes.Trek
N
6

None of the solutions offered here is a good solution. It may work for individual cases, but only if you're in control of the final display. Take my example: my work produces list of products they sell to retail. This is in CSV format and contain part-codes, some of them start with zero's, set by manufacturers (not under our control). Take away the leading zeroes and you may actually match another product. Retail customers want the list in CSV format because of back-end processing programs, that are also out of our control and different per customer, so we cannot change the format of the CSV files. No prefixed'=', nor added tabs. The data in the raw CSV files is correct; it's when customers open those files in Excel the problems start. And many customers are not really computer savvy. They can just about open and save an email attachment. We are thinking of providing the data in two slightly different formats: one as Excel Friendly (using the options suggested above by adding a TAB, the other one as the 'master'. But this may be wishful thinking as some customers will not understand why we need to do this. Meanwhile we continue to keep explaining why they sometimes see 'wrong' data in their spreadsheets. Until Microsoft makes a proper change I see no proper resolution to this, as long as one has no control over how end-users use the files.

Norward answered 30/11, 2017 at 10:59 Comment(1)
If an extra space on the left of your data doesn't matter, then you can fix Excel's problems by prepending "\xA0" (non-breaking-space) to your data.Patently
R
5

I have jus this week come across this convention, which seems to be an excellent approach, but I cannot find it referenced anywhere. Is anyone familiar with it? Can you cite a source for it? I have not looked for hours and hours but am hoping someone will recognize this approach.

Example 1: =("012345678905") displays as 012345678905

Example 2: =("1954-12-12") displays as 1954-12-12, not 12/12/1954.

Rollin answered 13/6, 2013 at 0:34 Comment(0)
R
5

Hi I have the same issue,

I write this vbscipt to create another CSV file. The new CSV file will have a space in font of each field, so excel will understand it as text.

So you create a .vbs file with the code below (for example Modify_CSV.vbs), save and close it. Drag and Drop your original file to your vbscript file. It will create a new file with "SPACE_ADDED" to file name in the same location.

Set objArgs = WScript.Arguments

Set objFso = createobject("scripting.filesystemobject")

dim objTextFile
dim arrStr ' an array to hold the text content
dim sLine  ' holding text to write to new file

'Looping through all dropped file
For t = 0 to objArgs.Count - 1
    ' Input Path
    inPath = objFso.GetFile(wscript.arguments.item(t))

    ' OutPut Path
    outPath = replace(inPath, objFso.GetFileName(inPath), left(objFso.GetFileName(inPath), InStrRev(objFso.GetFileName(inPath),".") - 1) & "_SPACE_ADDED.csv")

    ' Read the file
    set objTextFile = objFso.OpenTextFile(inPath)


    'Now Creating the file can overwrite exiting file
    set aNewFile = objFso.CreateTextFile(outPath, True) 
    aNewFile.Close  

    'Open the file to appending data
    set aNewFile = objFso.OpenTextFile(outPath, 8) '2=Open for writing 8 for appending

    ' Reading data and writing it to new file
    Do while NOT objTextFile.AtEndOfStream
        arrStr = split(objTextFile.ReadLine,",")

        sLine = ""  'Clear previous data

        For i=lbound(arrStr) to ubound(arrStr)
            sLine = sLine + " " + arrStr(i) + ","
        Next

        'Writing data to new file
        aNewFile.WriteLine left(sLine, len(sLine)-1) 'Get rid of that extra comma from the loop


    Loop

    'Closing new file
    aNewFile.Close  

Next ' This is for next file

set aNewFile=nothing
set objFso = nothing
set objArgs = nothing
Rhettrhetta answered 20/2, 2014 at 6:37 Comment(0)
T
5

(EXCEL 2007 and later)

How to force excel not to "detect" date formats without editing the source file

Either:

  • rename the file as .txt
  • If you can't do that, instead of opening the CSV file directly in excel, create a new workbook then go to
    Data > Get external data > From Text
    and select your CSV.

Either way, you will be presented with import options, simply select each column containing dates and tell excel to format as "text" not "general".

Thuja answered 17/9, 2015 at 9:39 Comment(0)
D
3

Its not the Excel. Windows does recognize the formula, the data as a date and autocorrects. You have to change the Windows settings.

"Control Panel" (-> "Switch to Classic View") -> "Regional and Language Options" -> tab "Regional Options" -> "Customize..." -> tab "Numbers" -> And then change the symbols according to what you want.

http://www.pcreview.co.uk/forums/enable-disable-auto-convert-number-date-t3791902.html

It will work on your computer, if these settings are not changed for example on your customers' computer they will see dates instead of data.

Disservice answered 8/5, 2014 at 11:51 Comment(1)
This will not solve anything. Maybe it protects the original date-like-looking fields but it will open up others to the same problem.Dreadful
B
3

Without modifying your csv file you can:

  1. Change the excel Format Cells option to "text"
  2. Then using the "Text Import Wizard" to define the csv cells.
  3. Once imported delete that data
  4. then just paste as plain text

excel will properly format and separate your csv cells as text formatted ignoring auto date formats.

Kind of a silly work around, but it beats modifying the csv data before importing. Andy Baird and Richard sort of eluded to this method, but missed a couple important steps.

Boiler answered 30/3, 2015 at 19:0 Comment(0)
I
3

In my case, "Sept8" in a csv file generated using R was converted into "8-Sept" by Excel 2013. The problem was solved by using write.xlsx2() function in the xlsx package to generate the output file in xlsx format, which can be loaded by Excel without unwanted conversion. So, if you are given a csv file, you can try loading it into R and converting it into xlsx using the write.xlsx2() function.

Idola answered 29/2, 2016 at 2:43 Comment(1)
I don't know why your answer is downvoted. It is useful to people at least who are using R. This answer helped me. Thanks :)Kaolinite
L
2

I know this is an old thread. For the ones like me, who still have this problem using Office 2013 via PowerShell COM object can use the opentext method. The problem is that this method has many arguments, that are sometimes mutual exclusive. To resolve this issue you can use the invoke-namedparameter method introduced in this post. An example would be

$ex = New-Object -com "Excel.Application"
$ex.visible = $true
$csv = "path\to\your\csv.csv"
Invoke-NamedParameter ($ex.workbooks) "opentext" @{"filename"=$csv; "Semicolon"= $true}

Unfortunately I just discovered that this method somehow breaks the CSV parsing when cells contain line breaks. This is supported by CSV but Microsoft's implementation seems to be bugged. Also it did somehow not detect German-specific chars. Giving it the correct culture did not change this behaviour. All files (CSV and script) are saved with utf8 encoding. First I wrote the following code to insert the CSV cell by cell.

$ex = New-Object -com "Excel.Application"
$ex.visible = $true;
$csv = "path\to\your\csv.csv";
$ex.workbooks.add();
$ex.activeWorkbook.activeSheet.Cells.NumberFormat = "@";
$data = import-csv $csv -encoding utf8 -delimiter ";"; 
$row = 1; 
$data | %{ $obj = $_; $col = 1; $_.psobject.properties.Name |%{if($row -eq1){$ex.ActiveWorkbook.activeSheet.Cells.item($row,$col).Value2= $_ };$ex.ActiveWorkbook.activeSheet.Cells.item($row+1,$col).Value2 =$obj.$_; $col++ }; $row++;}

But this is extremely slow, which is why I looked for an alternative. Apparently, Excel allows you to set the values of a range of cells with a matrix. So I used the algorithm in this blog to transform the CSV in a multiarray.

function csvToExcel($csv,$delimiter){
     $a = New-Object -com "Excel.Application"
     $a.visible = $true
     
    $a.workbooks.add()
     $a.activeWorkbook.activeSheet.Cells.NumberFormat = "@"
     $data = import-csv -delimiter $delimiter $csv; 
     $array = ($data |ConvertTo-MultiArray).Value
     $starta = [int][char]'a' - 1
     if ($array.GetLength(1) -gt 26) {
         $col = [char]([int][math]::Floor($array.GetLength(1)/26) + $starta) + [char](($array.GetLength(1)%26) + $Starta)
     } else {
         $col = [char]($array.GetLength(1) + $starta)
     }
     $range = $a.activeWorkbook.activeSheet.Range("a1:"+$col+""+$array.GetLength(0))
     $range.value2 = $array;
     $range.Columns.AutoFit();
     $range.Rows.AutoFit();
     $range.Cells.HorizontalAlignment = -4131
     $range.Cells.VerticalAlignment = -4160
}

 function ConvertTo-MultiArray {
     param(
         [Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
         [PSObject[]]$InputObject
     )
     BEGIN {
         $objects = @()
         [ref]$array = [ref]$null
     }
     Process {
         $objects += $InputObject
     }
     END {
         $properties = $objects[0].psobject.properties |%{$_.name}
         $array.Value = New-Object 'object[,]' ($objects.Count+1),$properties.count
         # i = row and j = column
         $j = 0
         $properties |%{
             $array.Value[0,$j] = $_.tostring()
             $j++
         }
         $i = 1
         $objects |% {
             $item = $_
             $j = 0
             $properties | % {
                 if ($item.($_) -eq $null) {
                     $array.value[$i,$j] = ""
                 }
                 else {
                     $array.value[$i,$j] = $item.($_).tostring()
                 }
                 $j++
             }
             $i++
         }
         $array
     } 
} 
csvToExcel "storage_stats.csv" ";"

You can use above code as is; it should convert any CSV into Excel. Just change the path to the CSV and the delimiter character at the bottom.

Lifesize answered 17/4, 2015 at 8:19 Comment(1)
too complicatedHolbrook
B
1

Okay found a simple way to do this in Excel 2003 through 2007. Open a blank xls workbook. Then go to Data menu, import external data. Select your csv file. Go through the wizard and then in "column data format" select any column that needs to be forced to "text". This will import that entire column as a text format preventing Excel from trying to treat any specific cells as a date.

Barsac answered 6/5, 2014 at 1:14 Comment(0)
A
1

This issue is still present in Mac Office 2011 and Office 2013, I cannot prevent it happening. It seems such a basic thing.

In my case I had values such as "1 - 2" & "7 - 12" within the CSV enclosed correctly within inverted commas, this automatically converts to a date within excel, if you try subsequently convert it to just plain text you would get a number representation of the date such as 43768. Additionally it reformats large numbers found in barcodes and EAN numbers to 123E+ numbers again which cannot be converted back.

I have found that Google Drive's Google Sheets doesnt convert the numbers to dates. The barcodes do have commas in them every 3 characters but these are easily removed. It handles CSVs really well especially when dealing with MAC / Windows CSVs.

Might save someone sometime.

Attrition answered 21/5, 2015 at 10:45 Comment(0)
V
1

EASIEST SOLUTION I just figured this out today.

  • Open in Word
  • Replace all hyphens with en dashes
  • Save and Close
  • Open in Excel

Once you are done editing, you can always open it back up in Word again to replace the en dashes with hyphens again.

Voltz answered 12/8, 2015 at 15:10 Comment(0)
O
1

I do this for credit card numbers which keep converting to scientific notation: I end up importing my .csv into Google Sheets. The import options now allow to disable automatic formatting of numeric values. I set any sensitive columns to Plain Text and download as xlsx.

It's a terrible workflow, but at least my values are left the way they should be.

Obituary answered 16/8, 2016 at 20:9 Comment(3)
I did bother, thank you. I hint at the automatic formatting selection being a new part of the import process. My answer provides a very specific workflow, for those who, like me, have been forced to use Sheets to deal with this specific problem. In my mind, this merited a separate answer. A minor adjustment of your tone might actually result in your comment being interpreted as helpful, which is the whole point of this family of websites.Obituary
But you can just use the Text Import in Excel to import the CSV file and not bother with Sheets, as noted in other answers.Squire
Is this credit card security PCI/DSS compatible? Should you be sharing credit card numbers with google?Animadvert
P
1

A workaround using Google Drive (or Numbers if you're on a Mac):

  1. Open the data in Excel
  2. Set the format of the column with incorrect data to Text (Format > Cells > Number > Text)
  3. Load the .csv into Google Drive, and open it with Google Sheets
  4. Copy the offending column
  5. Paste column into Excel as Text (Edit > Paste Special > Text)

Alternatively if you're on a Mac for step 3 you can open the data in Numbers.

Paraphrast answered 19/12, 2017 at 22:0 Comment(1)
This is a sane solution rather than working on it for hours without any resolution.Kauffmann
C
1

(EXCEL 2016 and later, actually I have not tried in older versions)

  1. Open new blank page
  2. Go to tab "Data"
  3. Click "From Text/CSV" and choose your csv file
  4. Check in preview whether your data is correct.
  5. In сase when some column is converted to date click "edit" and then select type Text by clicking on calendar in head of column
  6. Click "Close & Load"
Congressional answered 27/6, 2018 at 9:45 Comment(0)
J
1

If someone still looking for answer, the line below worked perfectly for me

I entered =("my_value").
i.e. =("04SEP2009") displayed as 04SEP2009 not as 09/04/2009

The same worked for integers more than 15 digits. They weren't getting trimmed anymore.

Jemie answered 20/1, 2021 at 17:42 Comment(0)
A
1

If you can change the file source data

If you're prepared to alter the original source CSV file, another option is to change the 'delimiter' in the data, so if your data is '4/11' (or 4-11) and Excel converts this to 4/11/2021 (UK or 11-4-2021 US), then changing the '/' or '-' character to something else will thwart the unwantwed Excel date conversion. Options may include:

  • Tilde ('~')
  • Plus ('+')
  • Underscore ('_')
  • Double-dash ('--')
  • En-dash (Alt 150)
  • Em-dash (Alt 151)
  • (Some other character!)

Note: moving to Unicode or other non-ascii/ansi characters may complicate matters if the file is to be used elsewhere.

So, '4-11' converted to '4~11' with a tilde will NOT be treated as a date!

For large CSV files, this has no additional overhead (ie: extra quotes/spaces/tabs/formula constructs) and just works when the file is opened directly (ie: double-clicking the CSV to open) and avoids pre-formatting columns as text or 'importing' the CSV file as text.

A search/replace in Notepad (or similar tool) can easily convert to/from the alternative delimiter, if necessary.

Import the original data

In newer versions of Excel you can import the data (outlined in other answers). In older versions of Excel, you can install the 'Power Query' add-in. This tool can also import CSVs without conversion. Choose: Power Query tab/From file/From Text-CSV, then 'Load' to open as a table. (You can choose 'do not detect data types' from the 'data type detection' options).

Animadvert answered 26/7, 2021 at 22:28 Comment(0)
S
0

I made this VBA macro which basically formats the output range as text before pasting the numbers. It works perfectly for me when I want to paste values such as 8/11, 23/6, 1/3, etc. without Excel interpreting them as dates.

Sub PasteAsText()
' Created by Lars-Erik Sørbotten, 2017-09-17
Call CreateSheetBackup
    
Columns(ActiveCell.Column).NumberFormat = "@"
    
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
DataObj.GetFromClipboard

ActiveCell.PasteSpecial

End Sub

I'm very interested in knowing if this works for other people as well. I've been looking for a solution to this problem for a while, but I haven't seen a quick VBA solution to it that didn't include inserting ' in front of the input text. This code retains the data in its original form.

Spectacle answered 17/9, 2017 at 16:4 Comment(0)
W
-1

If you put an inverted comma at the start of the field, it will be interpreted as text.

Example: 25/12/2008 becomes '25/12/2008

You are also able to select the field type when importing.

Weisbrodt answered 2/10, 2008 at 23:33 Comment(2)
I don't want a ' at the beginning of my data.Thagard
-1. The ' only works when entered directly in the excel, but it doesn't work in CSV - you'd have extra ' character in the excel cell after import.Matter
L
-1

An alternate method:

Convert the format of the column you want to change to 'Text'. Select all the cells you want to preserve, copy. Without deselecting those columns, click "Edit > Paste Special > As values"

Save as CSV. Note that this has to be the last thing you do to the file because when you reopen it, it will format itself as dates since cell formats cannot be saved in CSV files.

Lubricant answered 2/10, 2008 at 23:43 Comment(0)
C
-1

Paste table into word. Do a search/replace and change all - (dashes) into -- (double dash). Copy and paste into Excel. Can do same for other symbols (/), etc. If need to change back to a dash once in Excel, just format the column to text, then make the change. Hope this helps.

Clingstone answered 24/10, 2015 at 19:46 Comment(0)
C
-2

Prefixing space in double quotes resolved the issue!!

I had data like "7/8" in one of the .csv file columns and MS-Excel was converting it to date as "07-Aug". But with "LibreOffice Calc" there was no issue.

To resolve this, I just prefixed space character(added space before 7) like " 7/8" and it worked for me. This is tested for Excel-2007.

Clarhe answered 21/10, 2014 at 15:19 Comment(1)
OK, but then you have a space in the cell value. This may not be a problem, but invisible space at the start/end of cells often is...Bartlet
M
-4
SELECT CONCAT('\'',NOW(),'\''), firstname, lastname 
FROM your_table
INTO OUTFILE 'export.csv' 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '\"' 
LINES TERMINATED BY '\n'
Mukerji answered 24/2, 2011 at 8:10 Comment(1)
Rather than only post a block of code, please explain why this code solves the problem posed. Without an explanation, this is not an answer.Conlee
S
-5

CSV - comma separated values. Just create/edit through text editor instead of xls/xlsx/exel. In editing you can set date in required format and it must be kept intact. This is assuming same file is then getting processed programatically.

Sula answered 3/5, 2013 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.