Locked lesson.
About this lesson
Let's take what we've learned so far and put it to use with an exercise!
Exercise files
Download this lesson’s related exercise files.
22 - Create Excel Spreadsheet Using Python and Random Numbers.docx57.6 KB 22 - Create Excel Spreadsheet Using Python and Random Numbers SOLUTION.docx
56.8 KB
Quick reference
Create Excel Spreadsheet Using Python and Random Numbers
Let's take what we've learned so far and put it to use with an exercise!
When to use
Take a few minutes right now and try to do this exercise without refering to this guide.
Instructions
from openpyxl.workbook import Workbook
from openpyxl import load_workbook
from random import randint
#Create A Workbook
wb = Workbook()
# Set Active Worksheet
ws = wb.active
# Name Active Sheet "Salaries"
ws.title = "Salaries"
# Create list of 5 worker names
names = ["John", "Mary", "Steve", "Tina", "Bob"]
# Randomly generate salaries between $50,000 and $125,000
# from random import randint
# randint(50000, 125000)
# Create 2 Columns headers in A1 and B1: Names, Salaries
ws['A1'] = "Names"
ws['B1'] = "Salaries"
# Add Names and Salaries to Columns
starting_row = 2
for name in names:
ws.cell(row=starting_row, column=1).value = name
ws.cell(row=starting_row, column=2).value = randint(50000, 125000)
starting_row = starting_row + 1
# Save Spreadsheet as company_salaries.xlsx
wb.save('company_salaries.xlsx')
Hints & tips
- Have fun with this exercise!
Lesson notes are only available for subscribers.