How to diagonally split a cell, and fill in text on both parts in a spreadsheet using python ExcelWriter

Question:

I have a dataframe with made up values:

import pandas as pd
df = pd.DataFrame({'Country|Gender': ["US", "UK", "Canada"],
                   'Male': [100000, 10000, 1000],
                   'Female': [200000, 20000, 2000]})

Now I am put it to an excel:

from pandas import ExcelWriter
output_file='output.xlsx'
writer = ExcelWriter(output_file, engine='xlsxwriter')
df.to_excel(writer, 'FirstSheet', index=False)
writer.save()
writer.close()

I want to split the top-left cell of the dataframe on the spreadsheet diagonally, with "Country" in the bottom while "Gender" on the top.

How can I do that?

Asked By: xymzh

||

Answers:

IIUC, you can tweak the split with the engine you already set :

with ExcelWriter(output_file, engine="xlsxwriter") as writer:
    df.to_excel(writer, "FirstSheet", index=False)
    
    ws = writer.sheets["FirstSheet"]
    wb = writer.book

    fmt = wb.add_format({"diag_type": 2, "diag_color": "black"})
    fmt.set_text_wrap()
    fmt.set_border(1)
    fmt.set_bold()

    ws.write("A1", "{}GendernCountry".format(" "*15), fmt)
    ws.set_row(0, 29)
    ws.set_column("A:A", 13)

Output (output.xlsx):

enter image description here

Answered By: Timeless