Discovering the wonders of Python is an ever-surprising journey. Just when I thought I had seen it all, a new cool feature emerged before me. Recently, I stumbled upon a fascinating solution while exploring ways to create Excel workbooks with multiple worksheets. It’s called XlsxWriter – a Python module dedicated to crafting Excel XLSX files.
https://xlsxwriter.readthedocs.io/index.html
Below is a sample program to create an Excel Workbook with two worksheets.
#! /usr/bin/python3import os
import xlsxwriter# Function to write the 'Dream cars' worksheet
def write_sheet_cars():
worksheet = workbook.add_worksheet('Dream cars')# Formatting for header row
cell_format = workbook.add_format({'font_color': 'blue', 'bold': True, 'align': 'Left'})
row = 0
col = 0
worksheet.write(row, col, 'Name & model', cell_format)
worksheet.write(row, col + 1, 'Price (USD)', cell_format)# Formatting for data rows
cell_format = workbook.add_format({'font_color': 'black', 'num_format': '$###,###,##0', 'align': 'Right'})
row = row + 1
col = 0
worksheet.write(row, col, 'Alfa Romeo 8C 2900B Lungo Spider')
worksheet.write(row, col + 1, 19800000, cell_format)row = row + 1
col = 0
worksheet.write(row, col, '1955 Jaguar D-Type')
worksheet.write(row, col + 1, 21780000, cell_format)row = row + 1
col = 0
worksheet.write(row, col, '1957 Ferrari 335 Sport Scaglietti')
worksheet.write(row, col + 1, 35710000, cell_format)# Autofit the columns to fit the content
worksheet.autofit()# Function to write the 'Cool planes' worksheet
def write_sheet_planes():
worksheet = workbook.add_worksheet('Cool planes')# Formatting for header row
cell_format = workbook.add_format({'font_color': 'blue', 'bold': True, 'align': 'Left'})
row = 0
col = 0
worksheet.write(row, col, 'Name & model', cell_format)
worksheet.write(row, col + 1, 'Maximum speed (km/h)', cell_format)# Formatting for data rows
cell_format = workbook.add_format({'font_color': 'black', 'num_format': '###,###,##0', 'align': 'Right'})
row = row + 1
col = 0
worksheet.write(row, col, 'Mig 25')
worksheet.write(row, col + 1, 3000, cell_format)row = row + 1
col = 0
worksheet.write(row, col, 'F-15 Eagle')
worksheet.write(row, col + 1, 3087, cell_format)row = row + 1
col = 0
worksheet.write(row, col, 'Su-27 Flanker')
worksheet.write(row, col + 1, 2500, cell_format)# Autofit the columns to fit the content
worksheet.autofit()#
## Main processing
#os.system('clear')
# Create a new Excel workbook
workbook = xlsxwriter.Workbook('Excel_Workbook_From_Python.xlsx')# Write the 'Dream cars' worksheet
write_sheet_cars()# Write the 'Cool planes' worksheet
write_sheet_planes()# Close the workbook and save the changes
workbook.close()
>The "Dream cars" worksheet:
The "Cool planes" worksheet: