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.
You can install the module using the following command.
pip install openpyxl
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.
In the picture above you can see the data in the Xlsx file which we are going to convert into CSV file.
## 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
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!
What is Studytonight?
Made with by Abhishek Ahlawat
© 2019 Studytonight. All rights reserved.