I have written a code to import a .csv file (containing numbers) into an excel file through openpyxl. It works, however, all the cells have written the numbers to the excel
You need to convert the value from the CSV file to what you need. All values in CSV files are strings.
ws.cell('%s%s'%(column_letter, (row_index + 1))).value = int(cell)
ought to do it.
BTW. you might want to look at the ws.append()
method.
This is the first google result, and I spent more time than I would like to admit working on this. I hope it helps someone in the future.
def csvtoxlsx(csv_name, xlsx_name, directory, floats):
"""
A function to convert a CSV file to XLSX so it can be used by openpyxl.
csvname = file name of csv you want to convert (include .csv)
xlsx_name = name you want to name the xlsx file (include .xlsx)
cwd = directory to find csv file (can pass os.getcwd())
floats = A list of column indexes in which floats appear
"""
os.chdir(directory)
f = open(csv_name, 'rt')
csv.register_dialect('commas', delimiter=',')
reader = csv.reader(f, dialect='commas')
wb = Workbook()
dest_filename = xlsx_name
ws = wb.worksheets[0]
ws.title = xlsx_name[:-5]
for row_index, row in enumerate(reader):
for column_index, cell in enumerate(row):
column_letter = get_column_letter((column_index + 1))
if column_index in floats:
s = cell
#Handles heading row or non floats
try:
s = float(s)
ws[('%s%s'%(column_letter, (row_index + 1)))].value = s
except ValueError:
ws[('%s%s'%(column_letter, (row_index + 1)))].value = s
elif column_index not in floats:
#Handles openpyxl 'illigal chars'
try:
ws[('%s%s'%(column_letter, (row_index + 1)))].value = cell
except:
ws[('%s%s'%(column_letter, (row_index + 1)))].value = 'illigal char'
wb.save(filename = dest_filename)