Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create excel-compatible CSV file with python?

Tags:

python

csv

excel

I am trying to create a csv file using python that is truly Excel-compatible (I am using Excel 2007, if that makes any difference).

Here is the sort of thing I'm trying to do

import csv

data = [ ['9-1', '9-2', '9-3'] ]

fd = open('test.csv', 'wb')
try:
    writer = csv.writer(fd, dialect='excel', quotechar='"', quoting=csv.QUOTE_ALL)
    writer.writerows(data)

finally:
    fd.close()

This creates a csv file that contains:

"9-1","9-2","9-3"

When I load it in Excel, I get the columns:

09-Jan  09-Feb  09-Mar

[Grrr, thanks Excel. Seriously, what is the point of quotes?]

Now, I have read elsewhere that in order to get Excel to treat strings as literal they must be prefixed by an equals sign ="Like This". So what I really want to produce is:

="9-1",="9-2",="9-3"

Is there any way to do this with the csv module in python? I'm guessing it will involve creating a custom dialect, but I can't see any variable that would give me the desired result.

like image 361
Lee Netherton Avatar asked Nov 14 '11 16:11

Lee Netherton


People also ask

Can Python create CSV file?

DictWriter() class can be used to write to a CSV file from a Python dictionary. Here, file - CSV file where we want to write to. fieldnames - a list object which should contain the column headers specifying the order in which data should be written in the CSV file.

Can Python convert XLSX to CSV?

Python developers can easily load & convert XLSX files to CSV in just a few lines of code.

Can OpenPyXL work with CSV?

Converting a CSV file to ExcelYour code uses Python's csv module in addition to OpenPyXL. You create a function, csv_to_excel() , then accepts two arguments: csv_file - The path to the input CSV file. excel_file - The path to the Excel file that you want to create.


2 Answers

If your aim is just writing a list as a table on Excel. You can try below sample, where ";" and dialect='excel-tab' property enables us to switch between coloumns.

import csv

RESULTS = [
    ['val_col1;','val_col2;','val_col3']
]
resultFile = open("testExcel.csv",'wb')
resultWriter= csv.writer(resultFile, dialect='excel-tab')
resultWriter.writerows(RESULTS)
like image 55
kara Avatar answered Oct 04 '22 04:10

kara


The problem is that you're importing your CSV file into Excel using Excel's CSV importer. Counterintuitive, I know, but you should not import CSV files that way. Instead, import them as text files (i.e., name with a txt extension). Then you will have the opportunity to specify the type of each column and can properly choose Text for columns that look like dates to Excel.

If you're looking for a turnkey "here is a file you can open in Excel" approach, try xlwt (not my original recommendation pyXLWriter) and avoid CSV entirely.

like image 35
kindall Avatar answered Oct 04 '22 04:10

kindall