Dates wind up in the bottom right corner of a cell, apparently ignoring alignment settings from xlsxwriter. A MWE:
import pandas
df = pandas.DataFrame(
{
"ints": [1, 2, 3]
, 'primes': [2, 3, 5]
, 'odds': [1, 3, 5]
, 'fechas': ['2017-04-07', '2017-05-09', '2017-11-30']
}
)
df['fechas'] = pandas.to_datetime(df['fechas']).dt.date
print(df)
xlsx_writer = pandas.ExcelWriter(
'test.xlsx'
, engine='xlsxwriter'
, date_format='mm/dd/yyyy'
)
df.to_excel(xlsx_writer, sheet_name='Sheet1', index=False)
wb = xlsx_writer.book
ws = xlsx_writer.sheets['Sheet1']
dollar_format = '_($* #,##0.00" "_);_($* (#,##0.0);_($* "-"??_);_(@_)'
dollar_format_wb = wb.add_format({'num_format': dollar_format, 'valign': 'vcenter'})
centre_format_wb = wb.add_format({'align': 'center', 'valign': 'vcenter'})
ws.set_column('A:A', 25, centre_format_wb)
ws.set_column('B:B', 20, centre_format_wb)
ws.set_column('C:C', 15, centre_format_wb)
ws.set_column('D:D', 10, dollar_format_wb)
# The code below was included to generate the screenshot, but isn't
# strictly necessary for the MWE
shadedrow_format_wb = wb.add_format(
{
'bg_color': '#EEEEEE'
, 'left': 1
, 'left_color': '#FFFFFF'
}
)
for r in range(0, 2 + df.shape[0]):
ws.set_row(r + 1, 45)
print(r)
if r % 2 == 0:
# a kludge as we can't change cell range formats after the fact without re-entering cell contents
ws.conditional_format('A{:}:D{:}'.format(r, r), {'type': 'no_errors', 'format': shadedrow_format_wb})
print("\t", r)
xlsx_writer.save()
Columns A, B, and C should be centered horizontally, and all rows except the header should be height 45, with all cell contents centered vertically.
Everything works like it should, except for the date column. Is there a good reason that this shouldn't work? Is there a correct way of getting the date centred? Is it a bug? Is there a work-around?
I have also tried formatting the sheet first, and performing the df.to_excel()
last, with no effect.
Many thanks!