Excel公式

2024-04-18 11:37:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python还不熟悉。我想用python处理excel数据。我做了下面的代码。代码在我第一次启动时就起作用了。它检测excel文件中的所有数据,甚至公式。 问题是它第二次不起作用。这意味着缺少一列数据。这是有公式的列。我希望我的代码一直工作。 我注意到,当我第二次运行所有代码时,它不再检测公式。我的代码将公式解释为“NaN”,在读取数据时,我要求不要显示“NaN”。所以什么都没有。 第二句话是:如果我在第一次启动代码后保存excel文件,我的代码会再次工作。 我希望我的代码一直工作。 我的代码:

import pandas as pd
import numpy as np
import xlsxwriter
from openpyxl import load_workbook
from pandas import ExcelWriter
from pandas import ExcelFile

data=pd.read_excel("site.xlsx","Feuille1", keep_default_na=False, skiprows = [0,1],usecols=[1,2,3,4]) 
print(data)

totalballon=[]
b=[]
espece=np.where(data['Unnamed: 1']=='TOTAL Espèces')[0]
carte=np.where(data['Unnamed: 1']=='TOTAL CB')[0]
cheque=np.where(data['Unnamed: 1']=='TOTAL Chèque')[0]

articles=["Ballon bleu", "CH24 jaune", "Ballon rouge", "Chapeau", "Ballon vert", "Pantalon", "Fleurs"]

print(np.sum(data['Unnamed: 3'][espece]))
print(np.sum(data['Unnamed: 3'][carte]))
print(np.sum(data['Unnamed: 3'][cheque]))


for i in articles:
    nb=np.where(data['Unnamed: 1']==i)[0]
    b.append(np.sum(data['Unnamed: 0'][nb]))
print(b)

ballon=["Ballon bleu", "Ballon rouge", "Ballon vert"]

for j in ballon:
    nb=np.where(data['Unnamed: 1']==j)[0]
    totalballon.append(np.sum(data['Unnamed: 0'][nb]))
totalballon=[sum(totalballon)]
print(totalballon)

with pd.ExcelWriter('site.xlsx', engine='openpyxl') as writer:
    writer.book = load_workbook('site.xlsx')


    TOTALespece = np.sum(data['Unnamed: 3'][espece])
    TOTALcarte = np.sum(data['Unnamed: 3'][carte])
    TOTALcheque = np.sum(data['Unnamed: 3'][cheque])

    df1 = pd.DataFrame({'articles':articles})
    df2 = pd.DataFrame({'nombres':b})
    df3 = pd.DataFrame({'Total ballon':totalballon})

    dfe = pd.DataFrame({'TOTAL Espèces':[TOTALespece]})
    dfcarte = pd.DataFrame({'TOTAL CB':[TOTALcarte]})
    dfcheque = pd.DataFrame({'TOTAL Chèque':[TOTALcheque]})

    df1.to_excel(writer, "Feuille2", index=False)
    df2.to_excel(writer, "Feuille2", index=False, startcol=1)
    df3.to_excel(writer, "Feuille2", index=False, startcol=2)
    dfe.to_excel(writer, "Feuille2", index=False, startcol=3)
    dfcarte.to_excel(writer, "Feuille2", index=False, startcol=4)
    dfcheque.to_excel(writer, "Feuille2", index=False, startcol=5)
    writer.book.save('site.xlsx')
    writer.book.close()

Print(data) first time

Print(data) second time after launching the code

未命名的列3不再显示。在此列中有所有excel公式。 My github with the excel file and the python code


Tags: 代码importfalsedataframedatanpexcelwriter