Skip to content

Instantly share code, notes, and snippets.

@fabriziopandini
Last active March 31, 2016 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabriziopandini/8b94f14733bdce959f49af03e6a3aafb to your computer and use it in GitHub Desktop.
Save fabriziopandini/8b94f14733bdce959f49af03e6a3aafb to your computer and use it in GitHub Desktop.
Create excel file in python from a CSV
import os
import csv
from openpyxl import Workbook
from openpyxl.cell import get_column_letter
from openpyxl.styles import PatternFill
fill = PatternFill(start_color='3498DB',
end_color='3498DB',
fill_type='solid')
def writeHeader(ws, header):
for c, col in enumerate(header):
h = ws.cell(column=c + 1, row=1, value=col)
h.fill = fill
def cast(value, type): #TODO: COMPLETE!
if type == 'int':
return int(value)
elif type == 'date':
return "???"
else:
return value
def writeData(ws, file, toType):
reader = csv.reader(file, delimiter=';')
for r, row in enumerate(reader):
for c, col in enumerate(row):
_ = ws.cell(column=c + 1, row=r + 2, value=cast(col,toType[c]))
wb = Workbook()
ws1 = wb.active
ws1.title = "TEST" #TODO: CUSTOMIZE
writeHeader(ws1, ["C1", "C2", "C3"]) #TODO: CUSTOMIZE
with open("TEST.csv", 'rb') as file: #TODO: CUSTOMIZE
writeData(ws1, file, ["string", "string", "int"]) #TODO: CUSTOMIZE
dest_filename = 'TEST.xlsx' #TODO: CUSTOMIZE
if os.path.exists(dest_filename):
os.remove(dest_filename)
wb.save(filename = dest_filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment