Having an issue aligning the first column to the left. Not sure what's wrong here. The formatting seems to work for the top row.
I just want the first column's text to align to the left.
def export_to_xlsx(date):
global df
## CREATE PD DATAFRAME
all_mp_dict = scraper(date)
df = pd.DataFrame(all_mp_dict)
## WORKSHEET FORMATTING (TOP ROW - YELLOW BG COLOR)
workbook_loc = './mp_excel/mp_data_' date '.xlsx'
writer = pd.ExcelWriter(workbook_loc, engine='xlsxwriter')
df.to_excel(writer, sheet_name=date '_raw')
workbook = writer.book
worksheet = writer.sheets[date '_raw']
header_format = workbook.add_format({
'bold': True,
'text_wrap': True,
'valign': 'top',
'fg_color': '#FFFF00',
'border': 1})
for col_num, value in enumerate(df.columns.values):
worksheet.write(0, col_num 1, value, header_format)
## WORKSHEET FORMATTING (FIRST COLUMN - ALIGN LEFT)
a_format = workbook.add_format()
a_format.set_align('left')
worksheet.set_column('A:A', 100, a_format)
## TO_EXCEL
writer.close()
CodePudding user response:
The reason that the Excel column format isn't being applied to the first column of the dataframe is that Pandas has already applied a bold/centered format to the cell to highlight the index values. In Excel, and XlsxWriter, a cell format overrides a column format.
So you can chose to drop the index and add you own, with it's own format, in the same way you are overwriting the column headers.