python xlsxwriter: Keep header in excel when adding a table

2024/10/14 7:17:31

I have a panda dataframe that I write to a xslx file, and would like to add a table over that data. I would also like to keep the headers that I have already written, instead of adding them again. Is that possible?

Example:

import pandas as pd
import xlsxwriter as xw# random dataframe
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']), 'two' : pd.Series([5., 6., 7., 8.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)# write data to file
writer = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')
df.to_excel(writer,"sheet without table")
df.to_excel(writer,"sheet with table")
df.to_excel(writer,"sheet with table and header")# get sheets to add the tables
workbook  = writer.book
worksheet_table = writer.sheets['sheet with table']
worksheet_table_header = writer.sheets['sheet with table and header']# the range in which the table is
end_row = len(df.index)
end_column = len(df.columns)
cell_range = xw.utility.xl_range(0, 0, end_row, end_column)# add the table that will delete the headers
worksheet_table.add_table(cell_range,{'header_row': True,'first_column': True})######################################
# The hack# Using the index in the Table
df.reset_index(inplace=True)
header = [{'header': di} for di in df.columns.tolist()]
worksheet_table_header.add_table(cell_range,{'header_row': True,'first_column': True,'columns':header})writer.save()
Answer

The hack / work around is the only option (as seen from @jmcnamara). In short it is:

import pandas as pd
import xlsxwriter as xw# random dataframe
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']), 'two' : pd.Series([5., 6., 7., 8.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)# write data to file
writer = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')
df.to_excel(writer,"sheet with table and header")# get sheets to add the tables
workbook  = writer.book
worksheet_table_header = writer.sheets['sheet with table and header']# the range in which the table is
end_row = len(df.index)
end_column = len(df.columns)
cell_range = xw.utility.xl_range(0, 0, end_row, end_column)######################################
# The hack# Using the index in the Table
df.reset_index(inplace=True)
header = [{'header': di} for di in df.columns.tolist()]
worksheet_table_header.add_table(cell_range,{'header_row': True,'first_column': True,'columns':header})writer.save()
https://en.xdnf.cn/q/69436.html

Related Q&A

Unexpected tokens in !DOCTYPE html in PyCharm Community Edition

I am new in using PyCharm but I am loving it gradually. I am getting a red underline on <!DOCTYPE html> and the error is "Unexpected Token".Why PyCharm shows it? I cant understand.

Indexing a numpy array with a numpy array of indexes [duplicate]

This question already has answers here:Indexing a numpy array with a list of tuples(2 answers)Index multidimensional array with index array(1 answer)Closed 5 years ago.I have a 3D numpy array data and …

Input redirection with python

I have the following program to test input redirection in Python.a = int(raw_input("Enter a number: ")) b = raw_input("Enter a string: ") print "number entered = ", a prin…

TypeError: can only concatenate str (not numpy.int64) to str

I want to print the variable based on the index number based on the following dataset:Here I used the following code:import pandas as pdairline = pd.read_csv("AIR-LINE.csv")pnr = input("…

Saving scatterplot animations with matplotlib produces blank video file

I am having a very similar problem to this questionbut the suggested solution doesnt work for me. I have set up an animated scatter plot using the matplotlib animation module. This works fine when it i…

How to group near-duplicate values in a pandas dataframe?

If there are duplicate values in a DataFrame pandas already provides functions to replace or drop duplicates. In many experimental datasets on the other hand one might have near duplicates. How can one…

python looping and creating new dataframe for each value of a column

I want to create a new dataframe for each unique value of station.I tried below which gives me only last station data updated in the dataframe = tai_new.itai[station].unique() has 500 values.for i in t…

How to put more whitespace around my plots?

I have a figure that contains two subplots in two rows and one column like so:fig, (ax1, ax2) = subplots(nrows=2,ncols=1, )The two subplots are pie charts, therefore I want their axes to be square. Aft…

using ols from statsmodels.formula.api - how to remove constant term?

Im following this first example in statsmodels tutorial:http://statsmodels.sourceforge.net/devel/How do I specify not to use constant term for linear fit in ols?# Fit regression model (using the natur…

Is numerical encoding necessary for the target variable in classification?

I am using sklearn for text classification, all my features are numerical but my target variable labels are in text. I can understand the rationale behind encoding features to numerics but dont think t…