Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove default formatting in header when converting pandas DataFrame to excel sheet

This is something that has been answered and re-answered time and time again because the answer keeps changing with updates to pandas. I tried some of the solutions I found here and elsewhere online and none of them have worked for me on the current version of pandas. Does anyone know the current, March 2019, pandas 0.24.2, fix for removing the default styling that a DataFrame gives to its header when converting it to an excel sheet? Simply using xlsxwriter to overwrite the styling does not work because of an issue with precedence.

like image 212
ArthurH Avatar asked Mar 19 '19 16:03

ArthurH


People also ask

How do I remove a header in Excel using Python?

Just simply put header=False and for eliminating the index using index=False. If you want to learn more about Pandas then visit this Python Course designed by industrial experts.

How do I convert a DataFrame to an Excel file in Python?

Use pandas to_excel() function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.

How do I format a DataFrame in Excel?

You can write any data (lists, strings, numbers etc) to Excel, by first converting it into a Pandas DataFrame and then writing the DataFrame to Excel. To export a Pandas DataFrame as an Excel file (extension: . xlsx, . xls), use the to_excel() method.


1 Answers

Based largely on an example provided in the Xlsxwriter Docs (link here), the fully reproducible example below removes the default pandas header format in pandas 0.24.2. Of note is that in df.to_excel(), I'm changing the header and startrow parameters.

import xlsxwriter
import pandas as pd
import numpy as np

# Creating a dataframe 
df = pd.DataFrame(np.random.randn(100, 3), columns=list('ABC'))
column_list = df.columns
# Create a Pandas Excel writer using XlsxWriter engine.
writer = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')

df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False)

# Get workbook and worksheet objects
workbook  = writer.book
worksheet = writer.sheets['Sheet1']


for idx, val in enumerate(column_list):
    worksheet.write(0, idx, val)

writer.save()

print(pd.__version__)

Expected Output:

0.24.2

Expected Output

like image 63
patrickjlong1 Avatar answered Oct 23 '22 23:10

patrickjlong1