You can export data from Python to an Excel file using the openpyxl library. This library allows you to create, read, and write Excel files directly from Python.
Installation
First, install the openpyxl library using pip:
pip install openpyxl
Exporting Data
Here's a basic example of how to export data to an Excel file:
import openpyxl
# Create a new workbook and worksheet
workbook = openpyxl.Workbook()
worksheet = workbook.active
# Define data to export
data = [
['Name', 'Age', 'City'],
['John Doe', 30, 'New York'],
['Jane Smith', 25, 'London'],
['Peter Jones', 40, 'Paris']
]
# Write data to the worksheet
for row_index, row_data in enumerate(data):
for col_index, cell_value in enumerate(row_data):
worksheet.cell(row=row_index + 1, column=col_index + 1).value = cell_value
# Save the workbook
workbook.save('my_excel_file.xlsx')
This code will create a new Excel file named my_excel_file.xlsx
with the provided data.
Key Points:
- The
openpyxl.Workbook()
function creates a new Excel workbook. - The
workbook.active
property accesses the active worksheet within the workbook. - You can use the
worksheet.cell(row, column).value
method to set the value of a specific cell. - The
workbook.save(filename)
method saves the workbook to a file.
Additional Notes:
- You can use various formatting options with the
openpyxl
library, such as setting cell styles, adding charts, and more. - You can also export data from other data structures, like Pandas DataFrames, directly to Excel using the
to_excel()
method.