Sometimes, we want to write to an Excel spreadsheet with Python.
In this article, we’ll look at how to write to an Excel spreadsheet with Python.
How to write to an Excel spreadsheet with Python?
To write to an Excel spreadsheet with Python, we can use the Pandas DataFrame’s to_excel
method.
We’ve to install the openpyxl
in addition to Pandas.
To install it, we run:
pip install openpyxl
For instance, we write:
from pandas import DataFrame
l1 = [1, 2, 3, 4]
l2 = [1, 2, 3, 4]
df = DataFrame({'Stimulus Time': l1, 'Reaction Time': l2})
df.to_excel('test.xlsx', sheet_name='sheet1', index=False)
We have 2 lists l1
and l2
.
Then we create a DataFrame with the DataFrame
constructor.
We pass in a dictionary with l1
and l2
as values as the argument.
Next, we call to_excel
with the file path of the file to write to, we set the sheet_name
‘s title.
Conclusion
To write to an Excel spreadsheet with Python, we can use the Pandas DataFrame’s to_excel
method.
We’ve to install the openpyxl
in addition to Pandas.