You are on page 1of 5

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

TOPIC:
1.UPDATING A SPREADSHEET
2.SETTING THE FONT STYLE OF CELLS

NAME : RAKSHITH P S
USN :1VI20CS090
SEM :5
SEC :B
Updating a Spreadsheet
• Program does the following:
->Loops over all the rows.
->If the row is for garlic, celery, or lemons, changes the price.
• Code will do the following:
1:Open the spreadsheet file.
2: For each row, check whether the value in column A is Celery, Garlic, or
Lemon. If it is, update the price in column B.
3: Save the spreadsheet to a new file (so that you don’t lose the old
spreadsheet, just in case).
4 :To update cells in a spreadsheet of produce sales. Program will look
through the spreadsheet, find specific kinds of produce, and update their
prices.
Step 1: Set up a Data Structure with the Update Information
The flexible way is to store the information in a dictionary and we use this
data structure in the following code .
import openpyxl
wb = openpyxl.load_workbook(‘produceSales.xlsx’)
sheet = wb.get_sheet_by_name('Sheet’)
PRICE_UPDATES = {'Garlic': 3.07, 'Celery': 1.19, 'Lemon': 1.27}
• If further the table has to be updated ,we need to update only the dictionary
values ,either by removing or adding the key value pairs.
Step2:check all rows and then update
The below code loop through the row starting from 2 since row 1 is just the
header, the column values which is to updated is stored in the ‘produceName’
variable .If it exists in the dictionary then the column value is updated .
for rowNum in range(2, sheet.get_highest_row()):
produceName = sheet.cell(row=rowNum, column=1).value
if produceName in PRICE_UPDATES:
sheet.cell(row=rowNum, column=2).value = PRICE_UPDATES[produceName]
wb.save('updatedProduceSales.xlsx’)
• The complexity is reduced with just one if loop and using the dictionary
Setting the Font Style of Cells
• Styling is applied directly to the cells . Styling certain cells , rows and columns emphasize
important areas of the spreadsheet.
• To customize font styles in cells, import the Font() and Style() functions from the
openpyxl.styles module.
import openpyxl
from openpyxl.styles import Font, Style
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet’)
italic24Font = Font(size=24, italic=True)
styleObj = Style(font=italic24Font)
sheet['A1'].style = styleObj
sheet['A1'] = 'Hello world!’
wb.save('styled.xlsx’)

You might also like