CLOSE

   Python  openpyxl  Xlsx  CSV  
   Technology    Programming

Converting Xlsx file To CSV file using Python

           
 MAY 4, 2019   by hafeezulkareem

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!




       

Made with by Abhishek Ahlawat

© 2019 Studytonight.   All rights reserved.

DMCA.com Protection Status