为什么我的代码(应该放在 headers 列中)擦除整个 Excel sheet 空白而没有 headers?

Why did my code (that was supposed to put in column headers) wipe the whole Excel sheet blank with no headers?

我编写了这个简单的程序,用于将列 headers 写入 pre-existing Excel .xlsx 文件中数据 table 上方的空单元格。当我 运行 时我没有收到任何错误,但是当我打开文件时(使用单个 sheet),整个 table 都消失了,它是空白的;甚至没有任何应该写入的 headers。谁能帮我弄清楚为什么会这样?我可以再次获取数据,我只需要这个就可以了。

import pandas as pd
from openpyxl import load_workbook
headers = []

# code not shown, but just prompts user for column headers and saves in list 'headers'

#open .xlsx file
book = load_workbook(r'path.xlsx')
writer = pd.ExcelWriter(r'path.xlsx', engine='xlsxwriter') 

#write column headers from list into empty cells
writer.columns = headers[:]


#save and close
writer.save()
writer.close()
book.close()

你可以试试这个代码


import pandas as pd

# Read excel file (.xlsx)
book_df = pd.read_excel(r'path.xlsx')

# headers is list of header names like ['header_1','header_2','header_3']
book_df.columns = headers
book_df.to_excel(r'modified_file_name.xlsx',index=False)
# In case you want the file in the same name , make sure the file is not open else you may get permission error
book_df.to_excel(r'path.xlsx',index=False)