Make python csvwriter output ="<string>"

Question:

As per the answers to this question: Stop Excel from automatically converting certain text values to dates I am trying to create a CSV file using the csv module of python, with certain fields formatted as

"=""<string-that-looks-like-a-date>"

however I am being unable to get the CSV writer to generate output like that. If I use the default csvwriter (no special parameters), and pre-format my data, it tries to quote all my quotes, and I get output that looks like this:

"""=""""6/6"""

If I set the quoting level of the csv writer to QUOTE_NONE, then I get an “Error: need to escape, but no escape char set”. Explicitly setting an escape character causes all the quotes I put in to be escaped. Trying just adding an equal sign to my data results in excel showing

=<string_that_looks_like_a_date> 

And so it goes – every combination of Quoting and formatting data I have tried fails to output the desired format.

Is there any way to get the python csvwriter module to output something that excel will interpret as plain text without any extra characters showing up in excel?

Asked By: ibrewster

||

Answers:

def excel_literal_print( string ): 
    print("="{0}"".format(string) )

the output file needs to read (unless excel 2007)

value,="date",="time"
Answered By: corn3lius

You just need to prepend =" and append " to your data. For example:

import csv

with open('test.csv', 'wb') as f:
    w = csv.writer(f)
    data = 'Feb 11'
    w.writerow([data])  # Excel will interpret this as a date
    w.writerow(['="%s"' % data])  # This is what you want (old way)
    w.writerow(['="{0}"'.format(data)])  # Or this, same thing
    w.writerow([f'="{data}"'])  # Or this, also same thing

Note that the string interpolation using the .format() method is available in Python 2.6 and later. In Python 2.7, you can leave out the 0. The f-string interpolation was introduced in Python 3.6.

Answered By: John Y
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.