r/pythonhelp • • Feb 09 '22

How to convert csv to xlsx with openpyxl?

Hello everyone! I'am creating a code for convert csv to xlsx but my code has a problem, it can convert the values only to A1 collumn. How to make code to be can writing values from csv to any selected collumn?

My Code:

import csv

import openpyxl

wb = openpyxl.Workbook()

ws = wb.active

with open('text.csv') as f:

reader = csv.reader(f, delimiter=':')

for row in reader:

ws.append(row)

wb.save('file.xlsx')

2 Upvotes

2 comments sorted by

2

u/[deleted] Feb 09 '22

Looks fine to me, so just checked and it worked (two columns on my csv file).

I am assuming your code looks like the below, with regard to indentation:

import csv
import openpyxl

wb = openpyxl.Workbook()
ws = wb.active
with open('text.csv') as f:
    reader = csv.reader(f)  # comma default for me
    for row in reader:
        ws.append(row)
wb.save('file.xlsx')

NB. I used default comma delimiter - are you sure your data is parsed correctly? Worth printing out the row info in the loop to double check.

1

u/lullaby876 Feb 09 '22

Why not use pandas?

import pandas as pd

df = pd.read_csv('text.csv')

df.to_excel('text.xlsx')