Python Excel

Writing and Reading Excel Data from Python

Python is a very popular language for data analysis  and data manipulation. Furthermore, Python has a lot of libraries to manipulate Excel data. In this post, I will explain how to write to and read from  Excel sheet using Python’s script .  Which will be very useful for you to learn data science and Artificial Intelligence.

To perform reading and writing operation I will use two libraries  xlwt   and pandas   which are very popular  libraries for Excel data manipulation.

See the below program

import xlwt
import pandas as pd                                                        # Importing libraries

book = xlwt.Workbook()                                               # Open a Workbook
sheet1 = book.add_sheet(“Mysheet.xls”)               # Open an Excel  sheet in Workbook
sheet1.write(3, 2, 2000)                                               # Write data into 4th row and in 3rd column 
sheet1.write(3, 3, 120)                                                  # Write data into 4th row and in 4rd column 
sheet1.write(3, 4, 140)                                                  # Write data into 4th row and in 5th column 
book.save(‘Mysheet.xls’)                                             # Saving Workbook

excel_df=pd.read_excel(“Mysheet.xls”)             # Reading Excel data into  pandas Daframe 
print(excel_df)                                                              # Printing data

 

Python Excel

You can also understand  after reading comment, however,  I am going to explain the above code.

The two lines

import xlwt
import pandas as pd   

are used to import two libraries xlwt and pandas.

Statement  book = xlwt.Workbook()    this line creates a workbook object   of Python.

Statement  sheet1 = book.add_sheet(“Mysheet.xls”)    book object calls the function add_sheet()  and creates

a file Mysheet.xls and a Python  object sheet1.

write(row+1, col+1, data)  function of sheet object are used to  write data in  sheet1.

Statement     excel_df=pd.read_excel(“Mysheet.xls”)   create a  pandas dataframe, a Python’s dataframe is a two dimension data structure.

Finally,  print(excel_df)   statement prints data of    Mysheet.xls.

 

QR code for this post

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.