Из документации xlsxwriter здесь :
The columns parameter can be used to set properties for columns within the table.
The sub-properties that can be set are header, header_format etc.
The column data must be specified as a list of dicts.
Это означает, что вы можете добавить еще один ключ 'columnms' в словарь метода add_table для переименования заголовков.
Вот пример таблицы с переименованными заголовками:
import pandas as pd
df = pd.DataFrame({'Name': ['John','George','Paul'],
'Age': [23,34,42]})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# This will create a basic table with the headers named as 'Column 1' etc
#worksheet.add_table('A1:B4', {'data': df.values.tolist()})
# Add the 'columns' argument to name the headers
worksheet.add_table('A1:B4', {'data': df.values.tolist(),
'columns': [{'header': 'Name'},
{'header': 'Age'}]})
writer.save()
Вывод:
РЕДАКТИРОВАТЬ
Если ваш фрейм данных импортирован из файла, и вы не хотите вручную вводить все имена заголовков, вы можете сделать 'columns': [{'header': df.columns[0]}, {'header': df.columns[1]}]
et c или даже лучше объявить переменной и присвойте ей понимание списка:
header_names = [{'header': df.columns[x]} for x in range(df.shape[1])]
Тогда вам просто нужно сделать:
worksheet.add_table('A1:B4', {'data': df.values.tolist(),
'columns': header_names})