SlideShare a Scribd company logo
1 “Programming in Python With Openpyxl”
"PYTHON PROGRAMMING
With OPENPYXL "
Prepared by:
AMARjeetsingh thakur
2 “Programming in Python With Openpyxl”
1. INTRODUCTION
Openpyxl is a Python module to deal with Excel files without involving MS Excel
application software. It is used extensively in different operations from data copying to data
mining and data analysis by computer operators to data analysts and data scientists. openpyxl
is the most used module in python to handle excel files. If you have to read data from excel,
or you want to write data or draw some charts, accessing sheets, renaming sheets, adding or
deleting sheets, formatting and styling in sheets or any other task, openpyxl will do the job
for you.
If you want to Read, Write and Manipulate(Copy, cut, paste, delete or search for an item etc)
Excel files in Python with simple and practical examples we will suggest you to see this
simple and to the point Python Excel Openpyxl Course with examples about how to deal with
MS Excel files in Python. This course teaches efficiently how to manipulate excel files and
automate tasks.
Everything you do in Microsoft Excel, can be automated with Python. So why not use the
power of Python and make your life easy. You can make intelligent and thinking Excel
sheets, bringing the power of logic and thinking of Python to Excel which is usually static,
hence bringing flexibility in Excel and a number of opportunities.
Basics for Python excel openpyxl work:
 An Excel file is usually called as Spreadsheet, however in openpyxl we call it
Workbook.
 A single Workbook is usually saved in a file with extension .xlsx
 A Workbook may have as less as one sheet and as many as dozens of worksheets.
 Active sheet is the worksheet user is viewing or viewed before closing the file.
 Each sheet consists of vertical columns, known as Column starting from A.
 Each sheet consists of rows, called as Row. Numbering starts from 1.
 Row and column meet at a box called Cell. Each cell has specific address in reference
to Row and Column. The cell may contain number, formula or text.
 The grid of cells make the work area or worksheet in excel.
3 “Programming in Python With Openpyxl”
2. Python | Reading an excel file using openpyxl module
 Openpyxl is a Python library for reading and writing Excel (with extension
xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and
modify Excel files.
 For example, user might have to go through thousands of rows and pick out few
handful information to make small changes based on some criteria. Using Openpyxl
module, these tasks can be done very efficiently and easily.
 Use this command to install openpyxl module : pip install openpyxl
Code #1 : Program to print the particular cell value
# Python program to read an excel file
# import openpyxl module
import openpyxl
# Give the location of the file
path = "C:UsersAdminDesktopdemo.xlsx"
# To open the workbook
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
# Get workbook active sheet object
# from the active attribute
sheet_obj = wb_obj.active
# Cell objects also have row, column,
# and coordinate attributes that provide
# location information for the cell.
# Note: The first row or
# column integer is 1, not 0.
# Cell object is created by using
# sheet object's cell() method.
cell_obj = sheet_obj.cell(row = 1, column = 1)
# Print value of cell object
# using the value attribute
print(cell_obj.value)
Output :
STUDENT 'S NAME
Code #2 : Determine total number of rows
# import openpyxl module
import openpyxl
4 “Programming in Python With Openpyxl”
# Give the location of the file
path = "C:UsersAdminDesktopdemo.xlsx"
# to open the workbook
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
# print the total number of rows
print(sheet_obj.max_row)
Output :
6
Code #3 : Determine total number of columns
# importing openpyxl module
import openpyxl
# Give the location of the file
path = "C:UsersAdminDesktopdemo.xlsx"
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
# print total number of column
print(sheet_obj.max_column)
Output :
4
Code #4 : Print all columns name
# importing openpyxl module
import openpyxl
# Give the location of the file
path = "C:UsersAdminDesktopdemo.xlsx"
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
max_col = sheet_obj.max_column
# Loop will print all columns name
for i in range(1, max_col + 1):
cell_obj = sheet_obj.cell(row = 1, column = i)
print(cell_obj.value)
5 “Programming in Python With Openpyxl”
Output :
STUDENT 'S NAME
COURSE
BRANCH
SEMESTER
Code #5 : Print first column value
# importing openpyxl module
import openpyxl
# Give the location of the file
path = "C:UsersAdminDesktopdemo.xlsx"
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
m_row = sheet_obj.max_row
# Loop will print all values
# of first column
for i in range(1, m_row + 1):
cell_obj = sheet_obj.cell(row = i, column = 1)
print(cell_obj.value)
Output :
STUDENT 'S NAME
ANKIT RAI
RAHUL RAI
PRIYA RAI
AISHWARYA
HARSHITA JAISWAL
Code #6 : Print a particular row value
# importing openpyxl module
import openpyxl
# Give the location of the file
path = "C:UsersAdminDesktopdemo.xlsx"
# workbook object is created
wb_obj = openpyxl.load_workbook(path)
6 “Programming in Python With Openpyxl”
sheet_obj = wb_obj.active
max_col = sheet_obj.max_column
# Will print a particular row value
for i in range(1, max_col + 1):
cell_obj = sheet_obj.cell(row = 2, column = i)
print(cell_obj.value, end = " ")
Output :
ANKIT RAI B.TECH CSE 4
7 “Programming in Python With Openpyxl”
3. Python | Writing to an excel file using openpyxl module
Code #1 : Program to print an active sheet title name
# import openpyxl module
import openpyxl
# Call a Workbook() function of openpyxl
# to create a new blank Workbook object
wb = openpyxl.Workbook()
# Get workbook active sheet
# from the active attribute.
sheet = wb.active
# Once have the Worksheet object,
# one can get its name from the
# title attribute.
sheet_title = sheet.title
print("active sheet title: " + sheet_title)
Output :
active sheet title: Sheet
Code #2 : Program to change the Title name
# import openpyxl module
import openpyxl
# Call a Workbook() function of openpyxl
# to create a new blank Workbook object
wb = openpyxl.Workbook()
# Get workbook active sheet
# from the active attribute
sheet = wb.active
# One can change the name of the title
sheet.title = "sheet1"
print("sheet name is renamed as: " + sheet.title)
Output :
sheet name is renamed as: sheet1
8 “Programming in Python With Openpyxl”
Code #3 : Program to write to an Excel sheet
# import openpyxl module
import openpyxl
# Call a Workbook() function of openpyxl
# to create a new blank Workbook object
wb = openpyxl.Workbook()
# Get workbook active sheet
# from the active attribute
sheet = wb.active
# Cell objects also have row, column
# and coordinate attributes that provide
# location information for the cell.
# Note: The first row or column integer
# is 1, not 0. Cell object is created by
# using sheet object's cell() method.
c1 = sheet.cell(row = 1, column = 1)
# writing values to cells
c1.value = "ANKIT"
c2 = sheet.cell(row= 1 , column = 2)
c2.value = "RAI"
# Once have a Worksheet object, one can
# access a cell object by its name also.
# A2 means column = 1 & row = 2.
c3 = sheet['A2']
c3.value = "RAHUL"
# B2 means column = 2 & row = 2.
c4 = sheet['B2']
c4.value = "RAI"
# Anytime you modify the Workbook object
# or its sheets and cells, the spreadsheet
# file will not be saved until you call
# the save() workbook method.
wb.save("C:UsersuserDesktopdemo.xlsx")
Output :
9 “Programming in Python With Openpyxl”
Code #4 :Program to add Sheets in the Workbook
# import openpyxl module
import openpyxl
# Call a Workbook() function of openpyxl
# to create a new blank Workbook object
wb = openpyxl.Workbook()
sheet = wb.active
# Sheets can be added to workbook with the
# workbook object's create_sheet() method.
wb.create_sheet(index = 1 , title = "demo sheet2")
wb.save("C:UsersuserDesktopdemo.xlsx")
Output :
10 “Programming in Python With Openpyxl”
4. Python | Adjusting rows and columns of an excel file
using openpyxl module
Worksheet objects have row_dimensions and column_dimensions attributes that control row
heights and column widths. A sheet’s row_dimensions and column_dimensions are
dictionary-like values; row_dimensions contains RowDimension objects and
column_dimensions contains ColumnDimension objects. In row_dimensions, one can access
one of the objects using the number of the row (in this case, 1 or 2). In column_dimensions,
one can access one of the objects using the letter of the column (in this case, A or B).
Code #1 : Program to set the dimensions of the cells.
# import openpyxl module
import openpyxl
# Call a Workbook() function of openpyxl
# to create a new blank Workbook object
wb = openpyxl.Workbook()
# Get workbook active sheet
# from the active attribute.
sheet = wb.active
# writing to the specified cell
sheet.cell(row = 1, column = 1).value = ' hello '
sheet.cell(row = 2, column = 2).value = ' everyone '
# set the height of the row
sheet.row_dimensions[1].height = 70
# set the width of the column
sheet.column_dimensions['B'].width = 20
# save the file
wb.save('dimension.xlsx')
Output:
Merging the cells:
11 “Programming in Python With Openpyxl”
A rectangular area of cells can be merged into a single cell with the merge_cells() sheet
method. The argument to merge_cells() is a single string of the top-left and bottom-right cells
of the rectangular area to be merged.
Code #2 : Program to merge the cells.
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
# merge cell from A2 to D4 i.e.
# A2, B2, C2, D2, A3, B3, C3, D3, A4, B4, C4 and D4 .
# A2:D4' merges 12 cells into a single cell.
sheet.merge_cells('A2:D4')
sheet.cell(row = 2, column = 1).value = 'Twelve cells join together.'
# merge cell C6 and D6
sheet.merge_cells('C6:D6')
sheet.cell(row = 6, column = 6).value = 'Two merge cells.'
wb.save('merge.xlsx')
Output:
Unmerging the cells:
To unmerge cells, call the unmerge_cells() sheet method.
Code #3 : Program to unmerge the cells.
import openpyxl
wb = openpyxl.load_workbook('merge.xlsx')
sheet = wb.active
# unmerge the cells
sheet.unmerge_cells('A2:D4')
sheet.unmerge_cells('C6:D6')
wb.save('merge.xlsx')
12 “Programming in Python With Openpyxl”
Output:
Setting the font styles of the cells: To customize font styles in cells, important, import the
Font() function from the openpyxl.styles module.
Code #4 : Program to set the font of the text.
import openpyxl
# import Font function from openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb.active
sheet.cell(row = 1, column = 1).value = "Ankit Rai"
# set the size of the cell to 24
sheet.cell(row = 1, column = 1).font = Font(size = 24 )
sheet.cell(row = 2, column = 2).value = "Ankit Rai"
# set the font style to italic
sheet.cell(row = 2, column = 2).font = Font(size = 24, italic = True)
sheet.cell(row = 3, column = 3).value = "Ankit Rai"
# set the font style to bold
sheet.cell(row = 3, column = 3).font = Font(size = 24, bold = True)
sheet.cell(row = 4, column = 4).value = "Ankit Rai"
# set the font name to 'Times New Roman'
sheet.cell(row = 4, column = 4).font = Font(size = 24, name = 'Times New
Roman')
13 “Programming in Python With Openpyxl”
wb.save('styles.xlsx')
Output:
14 “Programming in Python With Openpyxl”
5. Python | How to copy data from one excel sheet to
another
In this section, we will learn how to copy data from one excel sheet to destination excel
workbook using openpyxl module in Python.
For working with excel files, we require openpyxl, which is a Python library that is used for
reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. For copying
one excel file to another, we first open both the source and destination excel files. Then we
calculate the total number of rows and columns in the source excel file and read a single cell
value and store it in a variable and then write that value to the destination excel file at a cell
position similar to that of the cell in source file. The destination file is saved.
Procedure –
1) Import openpyxl library as xl.
2) Open the source excel file using the path in which it is located.
Note: The path should be a string and have double backslashes () instead of single backslash
(). Eg: Path should be C:UsersDesktopsource.xlsx Instead
of C:UsersAdminDesktopsource.xlsx
3) Open the required worksheet to copy using the index of it. The index of worksheet ‘n’ is
‘n-1’. For example, the index of worksheet 1 is 0.
4) Open the destination excel file and the active worksheet in it.
5) Calculate the total number of rows and columns in source excel file.
6) Use two for loops (one for iterating through rows and another for iterating through
columns of the excel file) to read the cell value in source file to a variable and then write it to
a cell in destination file from that variable.
7) Save the destination file.
Code #1 : Program to copy data from one excel sheet to another
# importing openpyxl module
import openpyxl as xl;
# opening the source excel file
filename ="C:UsersAdminDesktoptrading.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
# opening the destination excel file
filename1 ="C:UsersAdminDesktoptest.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.active
# calculate total number of rows and
# columns in source excel file
mr = ws1.max_row
mc = ws1.max_column
# copying the cell values from source
# excel file to destination excel file
15 “Programming in Python With Openpyxl”
for i in range (1, mr + 1):
for j in range (1, mc + 1):
# reading cell value from source excel file
c = ws1.cell(row = i, column = j)
# writing the read value to destination excel file
ws2.cell(row = i, column = j).value = c.value
# saving the destination excel file
wb2.save(str(filename1))
Source File:
16 “Programming in Python With Openpyxl”
Output:
17 “Programming in Python With Openpyxl”
For more information contact:
amarjeetsinght@gmail.com
linkedin.com/in/amarjeetsingh-thakur-54915955

More Related Content

What's hot

Numpy tutorial
Numpy tutorialNumpy tutorial
Numpy tutorial
HarikaReddy115
 
Lists
ListsLists
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
Learnbay Datascience
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
Abid Kohistani
 
Python twisted
Python twistedPython twisted
Python twisted
Mahendra M
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Edureka!
 
Python : Data Types
Python : Data TypesPython : Data Types
Python NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | EdurekaPython NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | Edureka
Edureka!
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
lalithambiga kamaraj
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
AkshayAggarwal79
 
Python
PythonPython
Python
SHIVAM VERMA
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
Sivakumar R D .
 
Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
Navneet Prakash
 

What's hot (20)

Numpy tutorial
Numpy tutorialNumpy tutorial
Numpy tutorial
 
Lists
ListsLists
Lists
 
List in Python
List in PythonList in Python
List in Python
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Python twisted
Python twistedPython twisted
Python twisted
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
Python Matplotlib Tutorial | Matplotlib Tutorial | Python Tutorial | Python T...
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | EdurekaPython NumPy Tutorial | NumPy Array | Edureka
Python NumPy Tutorial | NumPy Array | Edureka
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
 
Pointers, virtual function and polymorphism
Pointers, virtual function and polymorphismPointers, virtual function and polymorphism
Pointers, virtual function and polymorphism
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Python
PythonPython
Python
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
 

Similar to Python openpyxl

Exploiting JXL using Selenium
Exploiting JXL using SeleniumExploiting JXL using Selenium
Exploiting JXL using Selenium
OSSCube
 
Import and Export Excel files using XLConnect in R Studio
Import and Export Excel files using XLConnect in R StudioImport and Export Excel files using XLConnect in R Studio
Import and Export Excel files using XLConnect in R Studio
Rupak Roy
 
Tutorials on Macro
Tutorials on MacroTutorials on Macro
Tutorials on Macro
Anurag Deb
 
PYTHON FOR SPREADSHEET USERS.pptx
PYTHON FOR SPREADSHEET USERS.pptxPYTHON FOR SPREADSHEET USERS.pptx
PYTHON FOR SPREADSHEET USERS.pptx
rmlkmrPphtt
 
Import and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R StudioImport and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R Studio
Rupak Roy
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
Haitham El-Ghareeb
 
Excel Scripting
Excel Scripting Excel Scripting
Excel Scripting
G C Reddy Technologies
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
C++ Homework Help
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
DavisMurphyB81
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
R.K.College of engg & Tech
 
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docx
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docxLab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docx
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docx
rennaknapp
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com
donaldzs157
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19
Max Kleiner
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
sadhana312471
 
Educational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdfEducational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdf
rajeshjangid1865
 
Module 4.pptx
Module 4.pptxModule 4.pptx
Module 4.pptx
charancherry185493
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
Mahmoud Samir Fayed
 
Vba
Vba Vba
CSC240 Programming Assignment 9 Stacks amp Queues Assig.pdf
CSC240 Programming Assignment 9 Stacks amp Queues Assig.pdfCSC240 Programming Assignment 9 Stacks amp Queues Assig.pdf
CSC240 Programming Assignment 9 Stacks amp Queues Assig.pdf
yuvarajm76
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptx
abhishek364864
 

Similar to Python openpyxl (20)

Exploiting JXL using Selenium
Exploiting JXL using SeleniumExploiting JXL using Selenium
Exploiting JXL using Selenium
 
Import and Export Excel files using XLConnect in R Studio
Import and Export Excel files using XLConnect in R StudioImport and Export Excel files using XLConnect in R Studio
Import and Export Excel files using XLConnect in R Studio
 
Tutorials on Macro
Tutorials on MacroTutorials on Macro
Tutorials on Macro
 
PYTHON FOR SPREADSHEET USERS.pptx
PYTHON FOR SPREADSHEET USERS.pptxPYTHON FOR SPREADSHEET USERS.pptx
PYTHON FOR SPREADSHEET USERS.pptx
 
Import and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R StudioImport and Export Excel Data using openxlsx in R Studio
Import and Export Excel Data using openxlsx in R Studio
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
Excel Scripting
Excel Scripting Excel Scripting
Excel Scripting
 
CPP homework help
CPP homework helpCPP homework help
CPP homework help
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.com
 
Module IV_updated(old).pdf
Module IV_updated(old).pdfModule IV_updated(old).pdf
Module IV_updated(old).pdf
 
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docx
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docxLab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docx
Lab_3- Objective- Experiment with Lists- Stacks- and Queues- Simulate.docx
 
ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com ECET 370 Exceptional Education - snaptutorial.com
ECET 370 Exceptional Education - snaptutorial.com
 
Maxbox starter19
Maxbox starter19Maxbox starter19
Maxbox starter19
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Educational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdfEducational Objectives After successfully completing this assignmen.pdf
Educational Objectives After successfully completing this assignmen.pdf
 
Module 4.pptx
Module 4.pptxModule 4.pptx
Module 4.pptx
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
Vba
Vba Vba
Vba
 
CSC240 Programming Assignment 9 Stacks amp Queues Assig.pdf
CSC240 Programming Assignment 9 Stacks amp Queues Assig.pdfCSC240 Programming Assignment 9 Stacks amp Queues Assig.pdf
CSC240 Programming Assignment 9 Stacks amp Queues Assig.pdf
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptx
 

More from Amarjeetsingh Thakur

“Introduction to MATLAB & SIMULINK”
“Introduction to MATLAB  & SIMULINK”“Introduction to MATLAB  & SIMULINK”
“Introduction to MATLAB & SIMULINK”
Amarjeetsingh Thakur
 
Python code for servo control using Raspberry Pi
Python code for servo control using Raspberry PiPython code for servo control using Raspberry Pi
Python code for servo control using Raspberry Pi
Amarjeetsingh Thakur
 
Python code for Push button using Raspberry Pi
Python code for Push button using Raspberry PiPython code for Push button using Raspberry Pi
Python code for Push button using Raspberry Pi
Amarjeetsingh Thakur
 
Python code for Buzzer Control using Raspberry Pi
Python code for Buzzer Control using Raspberry PiPython code for Buzzer Control using Raspberry Pi
Python code for Buzzer Control using Raspberry Pi
Amarjeetsingh Thakur
 
Arduino programming part 2
Arduino programming part 2Arduino programming part 2
Arduino programming part 2
Amarjeetsingh Thakur
 
Arduino programming part1
Arduino programming part1Arduino programming part1
Arduino programming part1
Amarjeetsingh Thakur
 
Python openCV codes
Python openCV codesPython openCV codes
Python openCV codes
Amarjeetsingh Thakur
 
Python Numpy Source Codes
Python Numpy Source CodesPython Numpy Source Codes
Python Numpy Source Codes
Amarjeetsingh Thakur
 
Steemit html blog
Steemit html blogSteemit html blog
Steemit html blog
Amarjeetsingh Thakur
 
Python OpenCV Real Time projects
Python OpenCV Real Time projectsPython OpenCV Real Time projects
Python OpenCV Real Time projects
Amarjeetsingh Thakur
 
Adafruit_IoT_Platform
Adafruit_IoT_PlatformAdafruit_IoT_Platform
Adafruit_IoT_Platform
Amarjeetsingh Thakur
 
Core python programming tutorial
Core python programming tutorialCore python programming tutorial
Core python programming tutorial
Amarjeetsingh Thakur
 
Introduction to Internet of Things (IoT)
Introduction to Internet of Things (IoT)Introduction to Internet of Things (IoT)
Introduction to Internet of Things (IoT)
Amarjeetsingh Thakur
 
Introduction to Node MCU
Introduction to Node MCUIntroduction to Node MCU
Introduction to Node MCU
Amarjeetsingh Thakur
 
Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)
Amarjeetsingh Thakur
 
Introduction to MQ Telemetry Transport (MQTT)
Introduction to MQ Telemetry Transport (MQTT)Introduction to MQ Telemetry Transport (MQTT)
Introduction to MQ Telemetry Transport (MQTT)
Amarjeetsingh Thakur
 
Arduino Interfacing with different sensors and motor
Arduino Interfacing with different sensors and motorArduino Interfacing with different sensors and motor
Arduino Interfacing with different sensors and motor
Amarjeetsingh Thakur
 
Image processing in MATLAB
Image processing in MATLABImage processing in MATLAB
Image processing in MATLAB
Amarjeetsingh Thakur
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
Amarjeetsingh Thakur
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
Amarjeetsingh Thakur
 

More from Amarjeetsingh Thakur (20)

“Introduction to MATLAB & SIMULINK”
“Introduction to MATLAB  & SIMULINK”“Introduction to MATLAB  & SIMULINK”
“Introduction to MATLAB & SIMULINK”
 
Python code for servo control using Raspberry Pi
Python code for servo control using Raspberry PiPython code for servo control using Raspberry Pi
Python code for servo control using Raspberry Pi
 
Python code for Push button using Raspberry Pi
Python code for Push button using Raspberry PiPython code for Push button using Raspberry Pi
Python code for Push button using Raspberry Pi
 
Python code for Buzzer Control using Raspberry Pi
Python code for Buzzer Control using Raspberry PiPython code for Buzzer Control using Raspberry Pi
Python code for Buzzer Control using Raspberry Pi
 
Arduino programming part 2
Arduino programming part 2Arduino programming part 2
Arduino programming part 2
 
Arduino programming part1
Arduino programming part1Arduino programming part1
Arduino programming part1
 
Python openCV codes
Python openCV codesPython openCV codes
Python openCV codes
 
Python Numpy Source Codes
Python Numpy Source CodesPython Numpy Source Codes
Python Numpy Source Codes
 
Steemit html blog
Steemit html blogSteemit html blog
Steemit html blog
 
Python OpenCV Real Time projects
Python OpenCV Real Time projectsPython OpenCV Real Time projects
Python OpenCV Real Time projects
 
Adafruit_IoT_Platform
Adafruit_IoT_PlatformAdafruit_IoT_Platform
Adafruit_IoT_Platform
 
Core python programming tutorial
Core python programming tutorialCore python programming tutorial
Core python programming tutorial
 
Introduction to Internet of Things (IoT)
Introduction to Internet of Things (IoT)Introduction to Internet of Things (IoT)
Introduction to Internet of Things (IoT)
 
Introduction to Node MCU
Introduction to Node MCUIntroduction to Node MCU
Introduction to Node MCU
 
Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)Introduction to Things board (An Open Source IoT Cloud Platform)
Introduction to Things board (An Open Source IoT Cloud Platform)
 
Introduction to MQ Telemetry Transport (MQTT)
Introduction to MQ Telemetry Transport (MQTT)Introduction to MQ Telemetry Transport (MQTT)
Introduction to MQ Telemetry Transport (MQTT)
 
Arduino Interfacing with different sensors and motor
Arduino Interfacing with different sensors and motorArduino Interfacing with different sensors and motor
Arduino Interfacing with different sensors and motor
 
Image processing in MATLAB
Image processing in MATLABImage processing in MATLAB
Image processing in MATLAB
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 

Recently uploaded

[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
introduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdfintroduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdf
ravindarpurohit26
 
Self-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptxSelf-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptx
iemerc2024
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
PauloRodrigues104553
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
skuxot
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 

Recently uploaded (20)

[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
introduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdfintroduction to solar energy for engineering.pdf
introduction to solar energy for engineering.pdf
 
Self-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptxSelf-Control of Emotions by Slidesgo.pptx
Self-Control of Emotions by Slidesgo.pptx
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
一比一原版(UC Berkeley毕业证)加利福尼亚大学|伯克利分校毕业证成绩单专业办理
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 

Python openpyxl

  • 1. 1 “Programming in Python With Openpyxl” "PYTHON PROGRAMMING With OPENPYXL " Prepared by: AMARjeetsingh thakur
  • 2. 2 “Programming in Python With Openpyxl” 1. INTRODUCTION Openpyxl is a Python module to deal with Excel files without involving MS Excel application software. It is used extensively in different operations from data copying to data mining and data analysis by computer operators to data analysts and data scientists. openpyxl is the most used module in python to handle excel files. If you have to read data from excel, or you want to write data or draw some charts, accessing sheets, renaming sheets, adding or deleting sheets, formatting and styling in sheets or any other task, openpyxl will do the job for you. If you want to Read, Write and Manipulate(Copy, cut, paste, delete or search for an item etc) Excel files in Python with simple and practical examples we will suggest you to see this simple and to the point Python Excel Openpyxl Course with examples about how to deal with MS Excel files in Python. This course teaches efficiently how to manipulate excel files and automate tasks. Everything you do in Microsoft Excel, can be automated with Python. So why not use the power of Python and make your life easy. You can make intelligent and thinking Excel sheets, bringing the power of logic and thinking of Python to Excel which is usually static, hence bringing flexibility in Excel and a number of opportunities. Basics for Python excel openpyxl work:  An Excel file is usually called as Spreadsheet, however in openpyxl we call it Workbook.  A single Workbook is usually saved in a file with extension .xlsx  A Workbook may have as less as one sheet and as many as dozens of worksheets.  Active sheet is the worksheet user is viewing or viewed before closing the file.  Each sheet consists of vertical columns, known as Column starting from A.  Each sheet consists of rows, called as Row. Numbering starts from 1.  Row and column meet at a box called Cell. Each cell has specific address in reference to Row and Column. The cell may contain number, formula or text.  The grid of cells make the work area or worksheet in excel.
  • 3. 3 “Programming in Python With Openpyxl” 2. Python | Reading an excel file using openpyxl module  Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files.  For example, user might have to go through thousands of rows and pick out few handful information to make small changes based on some criteria. Using Openpyxl module, these tasks can be done very efficiently and easily.  Use this command to install openpyxl module : pip install openpyxl Code #1 : Program to print the particular cell value # Python program to read an excel file # import openpyxl module import openpyxl # Give the location of the file path = "C:UsersAdminDesktopdemo.xlsx" # To open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) # Get workbook active sheet object # from the active attribute sheet_obj = wb_obj.active # Cell objects also have row, column, # and coordinate attributes that provide # location information for the cell. # Note: The first row or # column integer is 1, not 0. # Cell object is created by using # sheet object's cell() method. cell_obj = sheet_obj.cell(row = 1, column = 1) # Print value of cell object # using the value attribute print(cell_obj.value) Output : STUDENT 'S NAME Code #2 : Determine total number of rows # import openpyxl module import openpyxl
  • 4. 4 “Programming in Python With Openpyxl” # Give the location of the file path = "C:UsersAdminDesktopdemo.xlsx" # to open the workbook # workbook object is created wb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active # print the total number of rows print(sheet_obj.max_row) Output : 6 Code #3 : Determine total number of columns # importing openpyxl module import openpyxl # Give the location of the file path = "C:UsersAdminDesktopdemo.xlsx" # workbook object is created wb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active # print total number of column print(sheet_obj.max_column) Output : 4 Code #4 : Print all columns name # importing openpyxl module import openpyxl # Give the location of the file path = "C:UsersAdminDesktopdemo.xlsx" # workbook object is created wb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active max_col = sheet_obj.max_column # Loop will print all columns name for i in range(1, max_col + 1): cell_obj = sheet_obj.cell(row = 1, column = i) print(cell_obj.value)
  • 5. 5 “Programming in Python With Openpyxl” Output : STUDENT 'S NAME COURSE BRANCH SEMESTER Code #5 : Print first column value # importing openpyxl module import openpyxl # Give the location of the file path = "C:UsersAdminDesktopdemo.xlsx" # workbook object is created wb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active m_row = sheet_obj.max_row # Loop will print all values # of first column for i in range(1, m_row + 1): cell_obj = sheet_obj.cell(row = i, column = 1) print(cell_obj.value) Output : STUDENT 'S NAME ANKIT RAI RAHUL RAI PRIYA RAI AISHWARYA HARSHITA JAISWAL Code #6 : Print a particular row value # importing openpyxl module import openpyxl # Give the location of the file path = "C:UsersAdminDesktopdemo.xlsx" # workbook object is created wb_obj = openpyxl.load_workbook(path)
  • 6. 6 “Programming in Python With Openpyxl” sheet_obj = wb_obj.active max_col = sheet_obj.max_column # Will print a particular row value for i in range(1, max_col + 1): cell_obj = sheet_obj.cell(row = 2, column = i) print(cell_obj.value, end = " ") Output : ANKIT RAI B.TECH CSE 4
  • 7. 7 “Programming in Python With Openpyxl” 3. Python | Writing to an excel file using openpyxl module Code #1 : Program to print an active sheet title name # import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # Once have the Worksheet object, # one can get its name from the # title attribute. sheet_title = sheet.title print("active sheet title: " + sheet_title) Output : active sheet title: Sheet Code #2 : Program to change the Title name # import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute sheet = wb.active # One can change the name of the title sheet.title = "sheet1" print("sheet name is renamed as: " + sheet.title) Output : sheet name is renamed as: sheet1
  • 8. 8 “Programming in Python With Openpyxl” Code #3 : Program to write to an Excel sheet # import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute sheet = wb.active # Cell objects also have row, column # and coordinate attributes that provide # location information for the cell. # Note: The first row or column integer # is 1, not 0. Cell object is created by # using sheet object's cell() method. c1 = sheet.cell(row = 1, column = 1) # writing values to cells c1.value = "ANKIT" c2 = sheet.cell(row= 1 , column = 2) c2.value = "RAI" # Once have a Worksheet object, one can # access a cell object by its name also. # A2 means column = 1 & row = 2. c3 = sheet['A2'] c3.value = "RAHUL" # B2 means column = 2 & row = 2. c4 = sheet['B2'] c4.value = "RAI" # Anytime you modify the Workbook object # or its sheets and cells, the spreadsheet # file will not be saved until you call # the save() workbook method. wb.save("C:UsersuserDesktopdemo.xlsx") Output :
  • 9. 9 “Programming in Python With Openpyxl” Code #4 :Program to add Sheets in the Workbook # import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() sheet = wb.active # Sheets can be added to workbook with the # workbook object's create_sheet() method. wb.create_sheet(index = 1 , title = "demo sheet2") wb.save("C:UsersuserDesktopdemo.xlsx") Output :
  • 10. 10 “Programming in Python With Openpyxl” 4. Python | Adjusting rows and columns of an excel file using openpyxl module Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimensions contains ColumnDimension objects. In row_dimensions, one can access one of the objects using the number of the row (in this case, 1 or 2). In column_dimensions, one can access one of the objects using the letter of the column (in this case, A or B). Code #1 : Program to set the dimensions of the cells. # import openpyxl module import openpyxl # Call a Workbook() function of openpyxl # to create a new blank Workbook object wb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute. sheet = wb.active # writing to the specified cell sheet.cell(row = 1, column = 1).value = ' hello ' sheet.cell(row = 2, column = 2).value = ' everyone ' # set the height of the row sheet.row_dimensions[1].height = 70 # set the width of the column sheet.column_dimensions['B'].width = 20 # save the file wb.save('dimension.xlsx') Output: Merging the cells:
  • 11. 11 “Programming in Python With Openpyxl” A rectangular area of cells can be merged into a single cell with the merge_cells() sheet method. The argument to merge_cells() is a single string of the top-left and bottom-right cells of the rectangular area to be merged. Code #2 : Program to merge the cells. import openpyxl wb = openpyxl.Workbook() sheet = wb.active # merge cell from A2 to D4 i.e. # A2, B2, C2, D2, A3, B3, C3, D3, A4, B4, C4 and D4 . # A2:D4' merges 12 cells into a single cell. sheet.merge_cells('A2:D4') sheet.cell(row = 2, column = 1).value = 'Twelve cells join together.' # merge cell C6 and D6 sheet.merge_cells('C6:D6') sheet.cell(row = 6, column = 6).value = 'Two merge cells.' wb.save('merge.xlsx') Output: Unmerging the cells: To unmerge cells, call the unmerge_cells() sheet method. Code #3 : Program to unmerge the cells. import openpyxl wb = openpyxl.load_workbook('merge.xlsx') sheet = wb.active # unmerge the cells sheet.unmerge_cells('A2:D4') sheet.unmerge_cells('C6:D6') wb.save('merge.xlsx')
  • 12. 12 “Programming in Python With Openpyxl” Output: Setting the font styles of the cells: To customize font styles in cells, important, import the Font() function from the openpyxl.styles module. Code #4 : Program to set the font of the text. import openpyxl # import Font function from openpyxl from openpyxl.styles import Font wb = openpyxl.Workbook() sheet = wb.active sheet.cell(row = 1, column = 1).value = "Ankit Rai" # set the size of the cell to 24 sheet.cell(row = 1, column = 1).font = Font(size = 24 ) sheet.cell(row = 2, column = 2).value = "Ankit Rai" # set the font style to italic sheet.cell(row = 2, column = 2).font = Font(size = 24, italic = True) sheet.cell(row = 3, column = 3).value = "Ankit Rai" # set the font style to bold sheet.cell(row = 3, column = 3).font = Font(size = 24, bold = True) sheet.cell(row = 4, column = 4).value = "Ankit Rai" # set the font name to 'Times New Roman' sheet.cell(row = 4, column = 4).font = Font(size = 24, name = 'Times New Roman')
  • 13. 13 “Programming in Python With Openpyxl” wb.save('styles.xlsx') Output:
  • 14. 14 “Programming in Python With Openpyxl” 5. Python | How to copy data from one excel sheet to another In this section, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python. For working with excel files, we require openpyxl, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. For copying one excel file to another, we first open both the source and destination excel files. Then we calculate the total number of rows and columns in the source excel file and read a single cell value and store it in a variable and then write that value to the destination excel file at a cell position similar to that of the cell in source file. The destination file is saved. Procedure – 1) Import openpyxl library as xl. 2) Open the source excel file using the path in which it is located. Note: The path should be a string and have double backslashes () instead of single backslash (). Eg: Path should be C:UsersDesktopsource.xlsx Instead of C:UsersAdminDesktopsource.xlsx 3) Open the required worksheet to copy using the index of it. The index of worksheet ‘n’ is ‘n-1’. For example, the index of worksheet 1 is 0. 4) Open the destination excel file and the active worksheet in it. 5) Calculate the total number of rows and columns in source excel file. 6) Use two for loops (one for iterating through rows and another for iterating through columns of the excel file) to read the cell value in source file to a variable and then write it to a cell in destination file from that variable. 7) Save the destination file. Code #1 : Program to copy data from one excel sheet to another # importing openpyxl module import openpyxl as xl; # opening the source excel file filename ="C:UsersAdminDesktoptrading.xlsx" wb1 = xl.load_workbook(filename) ws1 = wb1.worksheets[0] # opening the destination excel file filename1 ="C:UsersAdminDesktoptest.xlsx" wb2 = xl.load_workbook(filename1) ws2 = wb2.active # calculate total number of rows and # columns in source excel file mr = ws1.max_row mc = ws1.max_column # copying the cell values from source # excel file to destination excel file
  • 15. 15 “Programming in Python With Openpyxl” for i in range (1, mr + 1): for j in range (1, mc + 1): # reading cell value from source excel file c = ws1.cell(row = i, column = j) # writing the read value to destination excel file ws2.cell(row = i, column = j).value = c.value # saving the destination excel file wb2.save(str(filename1)) Source File:
  • 16. 16 “Programming in Python With Openpyxl” Output:
  • 17. 17 “Programming in Python With Openpyxl” For more information contact: amarjeetsinght@gmail.com linkedin.com/in/amarjeetsingh-thakur-54915955