Home > other >  Creating Multiple Excel sheets using data frames Python pandas
Creating Multiple Excel sheets using data frames Python pandas

Time:02-07

I am trying to create Multiple Excel sheets using Python Pandas But its only creating the latest one and old one is getting replaced. Here my Scan2 Replaces Scan1 Sheet in output.xlsx file it's not saving the sheets.

import pandas as pd
from openpyxl import load_workbook

#scan1
df = pd.read_csv("C:/Users/t/Downloads/a.csv")

dfdf = df[df["Data"].str.contains("None") == False]

dfdf.to_excel("output.xlsx" , sheet_name= 'scan1' , index = False )

#scan2

dfg = pd.read_csv("C:/Users/t/Downloads/b.csv")

dfdfd = dfg[df["Data"].str.contains("None") == False]

dfdfd.to_excel("output.xlsx" , sheet_name= 'Scan2' , index=False)

CodePudding user response:

To save multiple sheets to excel, you have to use pandas' ExcelWriter method

try this:

writer = pd.ExcelWriter('output.xlsx', engine = 'xlsxwriter')

dfdf.to_excel(writer, sheet_name = 'Scan01')
dfdfd.to_excel(writer, sheet_name = 'Scan02')

other way of doing it without ExcelWriter installation:

with pd.ExcelWriter('output.xlsx') as writer:
     dfdf.to_excel(writer, sheet_name = 'Scan01')
     dfdfd.to_excel(writer, sheet_name = 'Scan02')
  •  Tags:  
  • Related