Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xlsxwriter in pandas and outside of pandas lockout

I am using xlsxwriter engine to push some dataframes into excel sheet with pandas.to_excel(), but I need a caption above each table.

Here is an example of what result I would like to achieve: enter image description here

I did not see any way to use ExcelWriter object of pandas to simply manipulate content of each cell and when I try to do it, I get:

Exception: Sheetname 'sample', with case ignored, is already in use.

I guess xlsxwriter locks it for itself. Here is an example:

xlsx_writer = pd.ExcelWriter(
    get_target_filepath(xlsx_name),
    engine='xlsxwriter'
)

workbook = xlsx_writer.book
worksheet = workbook.add_worksheet(sheet_name)

worksheet.write(1, 1, 'ABC')

_, sample_table = dataframe_tuples[0]
sample_table.to_excel(xlsx_writer, startrow=3, startcol=2, sheet_name=sheet_name)

I could save dataframes and go over it again with openpyxl, but I seriously dislike the way they do formatting, which I have to do next, and if I format it in xlsxwriter and then reopen it with openpyxl, it cannot save the formatting back properly, openpyxl ruins it.

I can not put excel itself onto server to use VBA macros for styling.

Is there any way around this or am I just doing something horribly wrong?

like image 316
Michal Fašánek Avatar asked Nov 23 '17 10:11

Michal Fašánek


Video Answer


1 Answers

You can do it as follows by getting the worksheet reference from pandas and calling standard XlsxWriter methods on it. Like this:

import pandas as pd


# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_example.xlsx', engine='xlsxwriter')

# Position the dataframes in the worksheet.
df1.to_excel(writer, sheet_name='Sheet1', index=False, startrow=2)
df2.to_excel(writer, sheet_name='Sheet1', index=False, startrow=9)

# Get the worksheet object.
worksheet = writer.sheets['Sheet1']

# Write some titles above the dataframes.
worksheet.write(1, 0, 'Some random title 1')
worksheet.write(8, 0, 'Some random title 2')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

See also Working with Python Pandas and XlsxWriter.

Output:

enter image description here

like image 50
jmcnamara Avatar answered Sep 27 '22 23:09

jmcnamara