r/pythonhelp • u/RD1706D • 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
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')
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:
NB. I used default comma delimiter - are you sure your data is parsed correctly? Worth printing out the
rowinfo in the loop to double check.