How to save a new sheet in an existing excel file, using Pandas?
Thank you. I believe that a complete example could be good for anyone else who have the same issue:
import pandas as pd
import numpy as np
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
df1.to_excel(writer, sheet_name = 'x1')
df2.to_excel(writer, sheet_name = 'x2')
writer.save()
writer.close()
Here I generate an excel file, from my understanding it does not really matter whether it is generated via the "xslxwriter" or the "openpyxl" engine.
When I want to write without loosing the original data then
import pandas as pd
import numpy as np
from openpyxl import load_workbook
path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)
x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)
df3.to_excel(writer, sheet_name = 'x3')
df4.to_excel(writer, sheet_name = 'x4')
writer.save()
writer.close()
this code do the job!
How can we write new data to existing Excel spreadsheet?
Please notes that Testing Append Process.xlsx
file has to be created before running this code.
from openpyxl import load_workbook
import pandas as pd
data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}
df = pd.DataFrame(data)
filename = "Testing Append Process.xlsx"
workbook = load_workbook(filename)
writer = pd.ExcelWriter(filename, engine='openpyxl')
writer.book = workbook
writer.sheets = {ws.title: ws for ws in workbook.worksheets}
df.to_excel(writer, startrow=writer.sheets['Sheet1'].max_row, index = False, header= False)
writer.close()
Returns the following if you will run the code twice.
Related Topics
How to Make a Tkinter Label Background Transparent
Find and Replace Specific Values Within 2D Array
Deal With Overflow in Exp Using Numpy
Spark Equivalent of If Then Else
Counting Number of Zeros Per Row by Pandas Dataframe
Find the Index of the First Digit in a String
Importing Local Module (Python Script) in Airflow Dag
How to Plot Multiple Pandas Columns
How to Download the Latest File of an S3 Bucket Using Boto3
How to Stop Python Script Using Command Line
Python: Pandas Pd.Read_Excel Giving Importerror: Install Xlrd >= 0.9.0 for Excel Support
Valueerror: Time Data Does Not Match Format When Parsing a Date
How to Make Python Get the Username in Windows and Then Implement It in a Script
How to Create a Multiline Plot Using Seaborn
How to Fix the 403:Insufficient Authentication Scopes Error from Google Analytics User Deletion API
Datetime.Datetime Has No Attribute Datetime
Valueerror: Cannot Reshape Array of Size 30470400 into Shape (50,1104,104)