Thursday, June 4, 2020

Create and save MS Excel Documents in Python

import openpyxl, pprint, os

"""
Writing Excel Documents
 Creating and Saving Excel Documents

"""
### Change dir to datafiles
os.chdir('/Google Drive/python_work/MyPythonScripts/datafiles')
# Verify datafiles is pwd
print(os.getcwd())

### Create a blank workbook.
wb = openpyxl.Workbook()
# It starts with one sheet.
print(wb.sheetnames)
sheet = wb.active
# Change the sheet name by storing a new string in its title attribute.
sheet.title = 'Duke Today Sheet'
print(wb.sheetnames)
print(sheet.title)

### Creating and Removing Sheets
# Sheets can be added and removed with the create_sheet() method and del operator.
# Add a new sheet.
wb.create_sheet()
print(wb.sheetnames)
# The create_sheet() method returns a new Worksheet object named SheetX, which by
# default is set to be the last sheet in the workbook. Optionally, the index and
# name of the new sheet can be specified with the index and title keyword arguments.
# Create a new sheet at index 0 and index 2
wb.create_sheet(index=0, title='First Sheet')
wb.create_sheet(index=2, title='Middle Sheet')
print(wb.sheetnames)
# Deleting a worksheet
del wb['Spam Bacon Eggs Sheet']
print(wb.sheetnames)

### Writing Values to Cells
sheet = wb['Sheet']
sheet['A1'] = 'Hello, world!'
print(sheet['A1'].value)

### Save workbook
# The spreadsheet file will not be saved until you call the save() workbook method
# with a name string.
wb.save('Workbook.xlsx')


No comments:

Post a Comment

Please add comments so I may update the material to accommodate platform modification to various commands. Also if you have some real-world caveats, do please share.

Search Duke

About the Author

My photo
Central Florida, United States