Python写入Excel文件后出现损坏恢复提示,求技术解决方案
Excel文件写入后提示损坏的问题排查与解决
问题场景
我有一个多标签页的XLSX文件,操作流程如下:
- 读取第3个标签页的特定单元格获取值(如ABC123),关闭文件。
- 从其他来源获取DataFrame,筛选出特定列包含该值的行。
- 将筛选后的DataFrame写入第5个标签页的指定位置:通过检查第15列是否存在“20 Jul”确定写入起始索引。
- 该标签页共15列,最后3列是公式未修改,仅写入DataFrame的12列。
所有操作无报错,但打开文件时会弹出文件已损坏,需要恢复的提示。尝试更换/移除engine问题依旧。
相关代码
def write_to_pcr(target_file_path, search_value, writer_df): # Name of Columns in PCR Report pcr_column_names = ['a','b','c'] print(f'target file path is {target_file_path}') pcr_data_df = pd.read_excel(target_file_path,index_col=None,skiprows=1,sheet_name='MS hours',usecols=pcr_column_names) # Filter the DataFrame based on the 'Revenue Period' column filtered_df = pcr_data_df[pcr_data_df['Revenue Period'].notna()] #& pcr_data_df['Revenue Period'].dt.strftime('%y').str.contains('24')] #print(filtered_df['Revenue Period'].dt.strftime('%Y-%m')) #print(filtered_df.head(10)) # Define the value to search for #search_value = '2024-07' pcr_data_df['Revenue Period'] = pcr_data_df['Revenue Period'].astype(str) # Find the index of the first occurrence of the given date #index = pcr_data_df['Revenue Period'].eq(search_value).idxmax() if pcr_data_df['Revenue Period'].str.contains(search_value).any(): #search_value in filtered_df['Revenue Period'].values: index = filtered_df['Revenue Period'].eq(search_value).idxmax() # Adding 3 to the current index value because while reading we are skiping 3 rows from the top , since # actual data starts from line 3. start_row_number=index+3 else: index = len(filtered_df['Revenue Period']) start_row_number=index print(f'index value when not found {index}') # Print the index print('index number is ',index+3) # Write the modified DataFrame back to the same Excel file with pd.ExcelWriter(target_file_path, engine = "openpyxl", mode = "a",if_sheet_exists = "overlay",date_format = 'dd/mm/yyyy') as writer: writer_df.to_excel(writer, sheet_name = "MS hours", index = False, startrow = start_row_number, header = False) print('Data has been populated to PCR report') #writer.close()
报错提示
Excel弹出提示:文件已损坏,需要恢复文件
可能的原因与解决方案
文件格式或引擎兼容性问题
- 使用
openpyxl追加模式时,若原文件由其他引擎(如xlrd)创建,可能引发格式冲突。建议先将原文件另存为标准XLSX格式,再执行写入操作。 - 避免直接修改原文件,先创建副本测试,确认无问题后再覆盖原文件。
- 使用
写入操作破坏原有结构
overlay模式可能意外覆盖公式列的格式或关联数据,即便未主动修改公式列。建议用openpyxl直接定位单元格写入,精准控制修改范围:from openpyxl import load_workbook wb = load_workbook(target_file_path) ws = wb['MS hours'] # 定位start_row_number后,逐行写入DataFrame的12列 for row_idx, row in enumerate(writer_df.itertuples(index=False), start=start_row_number): for col_idx, value in enumerate(row, start=1): ws.cell(row=row_idx, column=col_idx, value=value) wb.save(target_file_path)
日期格式处理不当
- 代码中将
Revenue Period转为字符串,可能破坏原文件的日期格式。建议保留日期类型进行匹配,避免不必要的类型转换。
- 代码中将
文件锁定或权限问题
- 确保操作时文件未被其他程序打开,写入前检查文件是否处于解锁状态。
内容的提问来源于stack exchange,提问作者Ashutosh Tiwari
相关产品推荐
相关产品推荐

