Ways to convert a CSV file to Excel file in Python 3

python-ways-to-convert-csv-to-excel-file-python-3-feature-image

In this tutorials, we’re gonna look at 4 ways to convert a CSV file to Excel file in Python 3. With each way, we use one of these module: xlwt, xlsxwriter, openpyxl and pandas.

Related Posts:
How to read/write CSV files in Python
How to read/write Excel files in Python
Node.js Extract MySQL Data to Excel(.xlsx) File – using exceljs

Convert CSV file to Excel file using xlwt

With this method, we:
– use csv module to open and read CSV file
– then use xlwt module to write and save Excel file

*Note: xlwt can only export Excel .xls files, not .xlsx files.

Example code:


import xlwt
import csv

wb = xlwt.Workbook()
sh = wb.add_sheet('gkz')

with open('ozenero.csv', 'r') as f:
    reader = csv.reader(f)
    for r, row in enumerate(reader):
        for c, val in enumerate(row):
            sh.write(r, c, val)
            
wb.save('ozenero.xls') # not .xlsx

Convert CSV file to Excel file using xlsxwriter

With this method, we:
- use csv module to open and read CSV file
- then use xlsxwriter module to write and save Excel file

Example code:


import xlsxwriter
import csv

wb = xlsxwriter.Workbook('ozenero.xlsx')
sh = wb.add_worksheet('gkz')

with open('ozenero.csv', 'r') as f:
    reader = csv.reader(f)
    for r, row in enumerate(reader):
        for c, val in enumerate(row):
            sh.write(r, c, val)
            
wb.close()

Convert CSV file to Excel file using openpyxl

With this method, we:
- use csv module to open and read CSV file
- then use openpyxl module to write and save Excel file

Example code:


import openpyxl
import csv

wb = openpyxl.Workbook()
sh = wb.create_sheet('gkz')

with open('ozenero.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        sh.append(row)
        
wb.save('ozenero.xlsx')

Convert CSV file to Excel file using pandas

With this method, we use only one module pandas to read Excel file and write data to CSV file.

Example code:


import pandas as pd

df = pd.read_csv('ozenero.csv')
df.to_excel('ozenero.xlsx', sheet_name='gkz', index=False)  # index=True to write row index
0 0 votes
Article Rating
Subscribe
Notify of
guest
1.7K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments