每次我用 Python 在 Excel 文件中写入内容时,Excel 文件都会被损坏

问题描述 投票:0回答:1

我正在尝试使用 pandas 更新我的 Excel 文件,但每次文件都会损坏 我再也打不开它了

1234.xlsx -> 表1

伽玛 伽马卫星 E50参考 EoedRef 欧洲参考 c Φ EA f.s
17.67 18.6 10500 10500 36000 4 24 4800
17.67 18.6 10500 10500 36000 4 36 7200

所以我想用Python代码填充f.s列 并在计算后立即写出每行的答案

main.py

import pandas as pd
import os
file_name = "1234.xlsx"
file_path =os.path.join(os.getcwd(),file_name)

df = pd.read_excel(file_path)

for index, row in df.iterrows():
    gammaUnsat = row['gammaUnsat']
    gammaSat = row['gammasat']
    E50ref = row['E50ref']
    EoedRef = row['EoedRef']
    EurRef = row['EurRef']
    c = row['c']
    phi = row['Φ']
    EA = row['EA']

    # some calculation

    #code to write in file
    df.loc[index , "f.s"] = sf_i

    writer = pd.ExcelWriter(path=file_path,engine="xlsxwriter")
    df.to_excel(writer,"Sheet1",index=False)

我没有任何错误,程序运行完美,但是当我单击 Excel 文件时,它告诉我该文件已损坏

enter image description here

python excel pandas xlsxwriter
1个回答
0
投票

我认为您可以在循环中随时创建描述符并打开/关闭文件,所以 (ps我不是测试代码) 但可能有效

import pandas as pd
import os
file_name = "1234.xlsx"
file_path = os.path.join(os.getcwd(), file_name)

df = pd.read_excel(file_path)

for index, row in df.iterrows():
    gammaUnsat = row['gammaUnsat']
    gammaSat = row['gammasat']
    E50ref = row['E50ref']
    EoedRef = row['EoedRef']
    EurRef = row['EurRef']
    c = row['c']
    phi = row['Φ']
    EA = row['EA']

    # some calculation

    #code to write in file
    df.loc[index, "f.s"] = sf_i

writer = pd.ExcelWriter(file_path, engine="xlsxwriter")
df.to_excel(writer, "Sheet1", index=False)
writer.save()
© www.soinside.com 2019 - 2024. All rights reserved.