In this tutorial, we will learn how to import a Python list into an Excel spreadsheet using the openpyxl library. The openpyxl library is widely used for working with Excel files as it provides a simple interface for reading and writing Excel files while maintaining the formatting.
Step 1: Install the openpyxl library
To use the openpyxl library, you need to install it first. You can install the library using the following command:
bash
pip install openpyxl
Step 2: Create a Python list
Now, let’s create a Python list that we want to put into an Excel file.
1 2 3 4 5 6 7 |
data_list = [ ['Name', 'Age', 'City'], ['John', 28, 'New York'], ['Jane', 24, 'San Francisco'], ['Alice', 22, 'Los Angeles'], ['Bob', 30, 'Chicago'] ] |
This list consists of a header row and four data rows.
Step 3: Create an Excel workbook and worksheet
After creating the list, you need to create a new Excel workbook and a worksheet using the openpyxl library.
1 2 3 4 |
import openpyxl workbook = openpyxl.Workbook() worksheet = workbook.active |
Step 4: Write the list to the worksheet
Now, you can write the data from the Python list to the Excel worksheet using a nested for loop. The first loop will iterate through each row, while the second loop will iterate through each cell of that row.
1 2 3 |
for row_num, row_data in enumerate(data_list, start=1): for col_num, cell_data in enumerate(row_data, start=1): worksheet.cell(row=row_num, column=col_num).value = cell_data |
Step 5: Save the workbook
Finally, after writing the data to the worksheet, you need to save the Excel workbook as an Excel file.
1 |
workbook.save(filename="output.xlsx") |
This will save the Excel file as “output.xlsx” in the current working directory.
Here is the complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import openpyxl data_list = [ ['Name', 'Age', 'City'], ['John', 28, 'New York'], ['Jane', 24, 'San Francisco'], ['Alice', 22, 'Los Angeles'], ['Bob', 30, 'Chicago'] ] workbook = openpyxl.Workbook() worksheet = workbook.active for row_num, row_data in enumerate(data_list, start=1): for col_num, cell_data in enumerate(row_data, start=1): worksheet.cell(row=row_num, column=col_num).value = cell_data workbook.save(filename="output.xlsx") |
Running this code will generate an Excel file with the following content:
Name Age City John 28 New York Jane 24 San Francisco Alice 22 Los Angeles Bob 30 Chicago
Conclusion
This tutorial demonstrated how to put a Python list into an Excel file using the openpyxl library. The process is simple: create a new Excel workbook, write the data from the Python list to the worksheet, and save it as an Excel file.
An openpyxl library is a powerful tool for working with Excel files in Python, providing a simple and efficient way to manipulate Excel data.