- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Python program to export dataframe into an Excel file with multiple sheets
Assume, you have a dataframe and the result for export dataframe to multiple sheets as,
To solve this, we will follow the steps given below −
Solution
import xlsxwriter module to use excel conversion
Define a dataframe and assign to df
Apply pd.ExcelWriter function inside name excel name you want to create and set engine as xlsxwriter
excel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter')
Convert the dataframe to multiple excel sheets using the below method,
df.to_excel(excel_writer, sheet_name='first_sheet') df.to_excel(excel_writer, sheet_name='second_sheet') df.to_excel(excel_writer, sheet_name='third_sheet')
Finally save the excel_writer
excel_writer.save()
Example
Let’s understand the below code to get a better understanding −
import pandas as pd import xlsxwriter df = pd.DataFrame({'Fruits': ["Apple","Orange","Mango","Kiwi"], 'City' : ["Shimla","Sydney","Lucknow","Wellington"] }) print(df) excel_writer = pd.ExcelWriter('pandas_df.xlsx', engine='xlsxwriter') df.to_excel(excel_writer, sheet_name='first_sheet') df.to_excel(excel_writer, sheet_name='second_sheet') df.to_excel(excel_writer, sheet_name='third_sheet') excel_writer.save()
Output
Advertisements