How To Put A Python List Into Excel

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.

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.

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.

Step 5: Save the workbook

Finally, after writing the data to the worksheet, you need to save the Excel workbook as an Excel file.

This will save the Excel file as “output.xlsx” in the current working directory.

Here is the complete code:

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.