save worksheet in openpyxl in python

To save a worksheet using openpyxl, you need to follow the following steps:

  • Create a workbook instance
  • Create or get a worksheet from the workbook using the workbook.create_sheet() method
  • Write data to the worksheet
  • Finally, save the workbook using workbook.save() method

Here's an example code snippet to illustrate the process:

main.py
from openpyxl import Workbook

# Creating a workbook instance
workbook = Workbook()

# Creating a worksheet named "Sheet1"
worksheet = workbook.create_sheet("Sheet1", 0)

# Writing some data to worksheet
worksheet["A1"] = "Name"
worksheet["A2"] = "Alice"
worksheet["A3"] = "Bob"
worksheet["A4"] = "Charlie"

# Saving the workbook
workbook.save("myworkbook.xlsx")
363 chars
17 lines

In the above example, we first created a workbook instance using the Workbook() method. Then we created a worksheet named "Sheet1" using the workbook.create_sheet() method. We then wrote some sample data to the worksheet. Finally, we saved the workbook using the workbook.save() method.

related categories

gistlibby LogSnag