Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy pandas dataframe to excel using openpyxl

Tags:

I have some complicated formating saved in a template file into which I need to save data from a pandas dataframe. Problem is when I use pd.to_excel to save to this worksheet, pandas overwrites the formatting. Is there a way to somehow 'paste values' form the df into the worksheet? I am using pandas 0.17

import openpyxl import pandas as pd wb= openpyxl.load_workbook('H:/template.xlsx') sheet = wb.get_sheet_by_name('spam') sheet.title = 'df data' wb.save('H:/df_out.xlsx')  xlr = pd.ExcelWriter('df_out.xlsx') df.to_excel(xlr, 'df data') xlr.save() 
like image 200
blitz009 Avatar asked Apr 15 '16 21:04

blitz009


People also ask

Can I use openpyxl and pandas together?

Load Excel data with openpyxl and convert to DataFrame . DataFrame is used to represent 2D data on Pandas. Since Excel data is also 2D data expressed by rows and columns, Worksheet object in [openpyxl] (https://openpyxl.readthedocs.io/en/stable/index.html) can be converted to Pandas DataFrame object.

Is openpyxl needed for pandas?

Importing openpyxl is required if you want to append it to an existing Excel file described at the end. You can specify a path as the first argument of the to_excel() method . Note: that the data in the original file is deleted when overwriting.


1 Answers

openpyxl 2.4 comes with a utility for converting Pandas Dataframes into something that openpyxl can work with directly. Code would look a bit like this:

from openpyxl.utils.dataframe import dataframe_to_rows rows = dataframe_to_rows(df)  for r_idx, row in enumerate(rows, 1):     for c_idx, value in enumerate(row, 1):          ws.cell(row=r_idx, column=c_idx, value=value) 

You can adjust the start of the enumeration to place the cells where you need them.

See openpyxl documentation for more information.

like image 179
Charlie Clark Avatar answered Oct 06 '22 18:10

Charlie Clark