Tuesday, October 23, 2012

Python CSV to XLS conversion script using openpyxl

Q. How to convert CSV file with ( : ) colon delimiter to Excel sheet?

A. Required - Python2.6 version with Openpyxl module

import csv
from openpyxl import Workbook
from openpyxl.cell import get_column_letter

f = open('/tmp/csvfile.txt', "rU")

csv.register_dialect('colons', delimiter=':')

reader = csv.reader(f, dialect='colons')

wb = Workbook()
dest_filename = r"/tmp/xls_out.xlsx"

ws = wb.worksheets[0]
ws.title = "A Snazzy Title"

for row_index, row in enumerate(reader):
    for column_index, cell in enumerate(row):
        column_letter = get_column_letter((column_index + 1))
        ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell

wb.save(filename = dest_filename)

1 comment: