SlideShare a Scribd company logo
1 of 17
Download to read offline
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

Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Edureka!
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An IntroductionSwarit Wadhe
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methodsnarmadhakin
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data typeswati kushwaha
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksEueung Mulyana
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesAndrew Ferlitsch
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in pythonJothi Thilaga P
 
Binary octal
Binary octalBinary octal
Binary octaldrdipo4
 
Data types in python lecture (2)
Data types in python lecture (2)Data types in python lecture (2)
Data types in python lecture (2)Ali ٍSattar
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Djangomcantelon
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 

What's hot (20)

Python - Lecture 11
Python - Lecture 11Python - Lecture 11
Python - Lecture 11
 
Python
PythonPython
Python
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
Python Sequence | Python Lists | Python Sets & Dictionary | Python Strings | ...
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Presentation on python data type
Presentation on python data typePresentation on python data type
Presentation on python data type
 
Introduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter NotebooksIntroduction to IPython & Jupyter Notebooks
Introduction to IPython & Jupyter Notebooks
 
Python - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning LibrariesPython - Numpy/Pandas/Matplot Machine Learning Libraries
Python - Numpy/Pandas/Matplot Machine Learning Libraries
 
Python
PythonPython
Python
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Binary octal
Binary octalBinary octal
Binary octal
 
Data types in python lecture (2)
Data types in python lecture (2)Data types in python lecture (2)
Data types in python lecture (2)
 
CSV Files-1.pdf
CSV Files-1.pdfCSV Files-1.pdf
CSV Files-1.pdf
 
Python array
Python arrayPython array
Python array
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Basic Crud In Django
Basic Crud In DjangoBasic Crud In Django
Basic Crud In Django
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Python list
Python listPython list
Python list
 

Similar to Python openpyxl

Exploiting JXL using Selenium
Exploiting JXL using SeleniumExploiting JXL using Selenium
Exploiting JXL using SeleniumOSSCube
 
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 StudioRupak Roy
 
Tutorials on Macro
Tutorials on MacroTutorials on Macro
Tutorials on MacroAnurag Deb
 
PYTHON FOR SPREADSHEET USERS.pptx
PYTHON FOR SPREADSHEET USERS.pptxPYTHON FOR SPREADSHEET USERS.pptx
PYTHON FOR SPREADSHEET USERS.pptxrmlkmrPphtt
 
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 StudioRupak Roy
 
Ecet 370 Education Organization -- snaptutorial.com
Ecet 370   Education Organization -- snaptutorial.comEcet 370   Education Organization -- snaptutorial.com
Ecet 370 Education Organization -- snaptutorial.comDavisMurphyB81
 
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.docxrennaknapp
 
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 starter19Max 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 2sadhana312471
 
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.pdfrajeshjangid1865
 
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 84Mahmoud Samir Fayed
 
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.pdfyuvarajm76
 
PRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxPRESENTATION ON PYTHON.pptx
PRESENTATION ON PYTHON.pptxabhishek364864
 

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 PiAmarjeetsingh 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 PiAmarjeetsingh 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 PiAmarjeetsingh 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 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 motorAmarjeetsingh 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

APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 

Recently uploaded (20)

APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 

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