You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel修改后openpyxl无法读取.xlsx文件问题求助

问题:Mac版Excel修改后openpyxl无法读取文件

我需要从Jira获取工单,在Excel中修改后批量更新回Jira。目前能成功将Jira数据写入Excel,代码如下:

# Write the DataFrame to an Excel file using openpyxl
excel_file = "jira_tickets.xlsx"
with pd.ExcelWriter(excel_file, engine='openpyxl') as writer:
    df.to_excel(writer, index=False, sheet_name='Tickets')

print(f"Data written to {excel_file} successfully.")

文件刚创建时能正常读取,代码如下:

# Check if the file can be opened with openpyxl
workbook = load_workbook(file_path)
print(f"Workbook '{file_path}' loaded successfully.")

# Load the first sheet
sheet = workbook.active
print(f"Sheet '{sheet.title}' loaded successfully.")

但用*Mac版Excel(16.89)*修改文件内容并保存后,上述读取代码会报错,提示文件不是有效的Excel文件或无法读取。我确认Excel可以正常打开、修改、保存并重新打开该文件,但openpyxl无法读取。

以下是验证文件有效性的代码:

def is_excel_file(file_path):
    try:
        # Check if the file is a valid Excel MIME type
        mime_type, _ = mimetypes.guess_type(file_path)
        if mime_type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
            print(f"File is not a valid Excel file: {file_path}")
            return False

        # Check if the file can be opened with openpyxl
        workbook = load_workbook(file_path)
        print(f"Workbook '{file_path}' loaded successfully.")
        
        # Load the first sheet
        sheet = workbook.active
        print(f"Sheet '{sheet.title}' loaded successfully.")
        
        # Print the first few rows
        row_count = 0
        for row in sheet.iter_rows(min_row=1, max_row=5, values_only=True):
            print(row)
            row_count += 1
        
        if row_count == 0:
            print("No data found in the first 5 rows.")
        
        return True
    except Exception as e:
        print(f"Error while checking if file is a valid Excel file with openpyxl: {e}")
        return False

# Explicitly reference the filename 'jira_tickets.xlsx'
file_name = 'jira_tickets.xlsx'
if is_excel_file(file_name):
    print(f"File '{file_name}' is a valid Excel file and has been read successfully.")
else:
    print(f"File '{file_name}' is not a valid Excel file or could not be read.")

运行验证代码时出现如下错误:

Error while checking if file is a valid Excel file with openpyxl: File is not a zip file
File 'jira_tickets.xlsx' is not a valid Excel file or could not be read.

测试步骤:

  • 运行代码读取文件并打印前几行(成功)
  • 在Excel中修改任意单元格内容,退出Excel
  • 运行代码读取文件(触发上述错误)
  • 再次用Excel打开文件(正常打开)

内容的提问来源于stack exchange,提问作者APythonCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 10:05:02