Technology3 min read

Converting Xlsx file To CSV file using Python

Abhishek Ahlawat

By Abhishek Ahlawat โ€” Recently

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

Summarize this article using AI

In the previous article covering working with Xlsx file in Python, we covered various methods of the openpyxl module of python to create, modify and analyse Xlsx files. In this article we will learn how to convert an Xlsx file to a CSV file using the openpyxl module and Python.

converting xlsx file to csv file in python


You can install the module using the following command.

pip install openpyxl



Converting Xlsx file To CSV file

Following are the steps to convert an Xlsx file to a CSV file:

1. Get the data from the Xlsx file using the openpyxl module.

2. Store every row of data in CSV file with comma separated values.

3. Save the file with .csv extension.

convert xlsx file to csv file using openpyxl module of python

In the picture above you can see the data in the Xlsx file which we are going to convert into CSV file.




Python Code

## XLSX TO CSV
import openpyxl

filename = 'appending.xlsx'

## opening the xlsx file
xlsx = openpyxl.load_workbook(filename)

## opening the active sheet
sheet = xlsx.active

## getting the data from the sheet
data = sheet.rows

## creating a csv file
csv = open("data.csv", "w+")

for row in data:
    l = list(row)
    for i in range(len(l)):
        if i == len(l) - 1:
            csv.write(str(l[i].value))
        else:
            csv.write(str(l[i].value) + ',')
        csv.write('\n')

## close the csv file
csv.close()

Once the program executes successfully, open the file data.csv

convert xlsx file to csv file using openpyxl module of python




Conclusion

You can convert any Xlsx sheet into CSV file using the above program by slightly changing the code according to your data. If you have any doubts regarding the article, mention them in the comment section.


SHARE YOUR THOUGHTS WITH US!



Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next