How To Create Multiple Sheets In Excel Using Python

In this tutorial, you will learn how to write multiple sheets in an Excel file using Python. We can achieve this task by leveraging the powerful pandas and openpyxl libraries. Pandas provide a straightforward and easy way to work with data in various formats, and openpyxl allows us to interact with Excel files in a simple manner.

Step 1: Import Required Libraries

First, you need to import the necessary libraries, which are pandas and openpyxl, into your Python script.

Step 2: Create Sample DataFrames

For this tutorial, let’s create two sample DataFrames with some data that we will write into separate Excel sheets.

Step 3: Create an Excel Writer Object

We need an Excel writer object to write our DataFrames to an Excel file. The writer object must be created with the desired Excel file name and the engine parameter set to ‘openpyxl’.

Step 4: Write DataFrames to Excel Sheets

Now, we will write our DataFrames into separate sheets of the same Excel file. You can do this by calling the to_excel() method on the DataFrame and passing the writer object, sheet name, and index parameter.

Step 5: Save the Excel File

Finally, you need to save the Excel file by calling the save() method on the writer object.

After running your script, you should see an Excel file named ‘output.xlsx’ generated in the same directory as your script.

Full Code

Here’s the complete code for the tutorial.

Output

Conclusion

In this tutorial, we learned how to write multiple sheets in an Excel file using Python. We leveraged the popular pandas library to create and manipulate the data, and the openpyxl library to write the data to an Excel file. This technique can be extremely useful when you need to store and manage different sets of data in a single file.