Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

openpyxl convert CSV to EXCEL

How can I convert a CSV file with : delimiter to XLS (Excel sheet) using openpyxl module?

like image 231
Satish Avatar asked Oct 19 '12 14:10

Satish


2 Answers

A much simpler, minimalist solution:

import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active

with open('file.csv') as f:
    reader = csv.reader(f, delimiter=':')
    for row in reader:
        ws.append(row)

wb.save('file.xlsx')
like image 132
Adam Stewart Avatar answered Oct 21 '22 20:10

Adam Stewart


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

f = open(r'C:\Users\Asus\Desktop\herp.csv')

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

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

wb = Workbook()
dest_filename = r"C:\Users\Asus\Desktop\herp.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)
like image 23
John Avatar answered Oct 21 '22 20:10

John