You can create Excel files in Python using the openpyxl
library. Here is an example of how to create an Excel file with a single worksheet and add some data to it:
pythonimport openpyxl
# Create a new Excel workbook
workbook = openpyxl.Workbook()
# Select the active worksheet
worksheet = workbook.active
# Add some data to the worksheet
worksheet['A1'] = 'Name'
worksheet['B1'] = 'Age'
worksheet['A2'] = 'John'
worksheet['B2'] = 25
worksheet['A3'] = 'Sarah'
worksheet['B3'] = 30
# Save the workbook
workbook.save('example.xlsx')
In this example, we create a new Excel workbook using openpyxl.Workbook()
. Then, we select the active worksheet using the active
property of the workbook. We add some data to the worksheet by accessing specific cells using their letter and number coordinates. Finally, we save the workbook using the save
method and passing in the filename we want to save the file as (in this case, 'example.xlsx').
You can customize the worksheet further by changing the formatting, adding formulas, and more. The openpyxl
library provides a wide range of functionality for working with Excel files in Python.
Comments
Post a Comment