如何使用循环将数据写入1个工作簿中的多个Excel工作表

问题描述

我希望这段代码遍历我的df,并将每个循环写到1个单一工作簿中的新工作表中。目前,它仅写出最后一次迭代。似乎每次都在工作表上进行复制,而不是添加新表。任何帮助将不胜感激

from pandas import Series,ExcelWriter
outputDF = pd.DataFrame(columns=['INDEX NAME','TICKER','ANALYST','PROFORMA INDEX SHARES','PRICE','MRKT VALUE','WEIGHT'])

firstRow = False
rowcount = 0

for (i,row) in final.iterrows():
    
    rowcount = rowcount + 1
    Index = final.loc[i,'INDEX NAME']
    Ticker = final.loc[i,'TICKER']
    Analyst = final.loc[i,'ANALYST']
    Shares = final.loc[i,'Proforma INDEX SHARES']
    Price = final.loc[i,'PRICE']
    MrktVal = final.loc[i,'MRKT VALUE']
    Weight = final.loc[i,'index_wgt']
    
    if firstRow == False:   
        oldanalyst = Analyst
        firstRow = True
        
        
    if oldanalyst != Analyst or rowcount == len(final):
        if rowcount == len(final):
            # append to outputDF. Just give values to columns with data,othwise it will be blank.
            outputDF = outputDF.append({'INDEX NAME':Index,'TICKER':Ticker,'ANALYST':Analyst,'PROFORMA 
        INDEX SHARES':Shares,'PRICE':Price,'MRKT VALUE':MrktVal,'WEIGHT':Weight},ignore_index=True)
            
        #Write out excel file,at last line of unique analyst
        filename =  r'C:\Users\Documents\Work\Weight.xlsx'
        ExcelWriter = pd.ExcelWriter(filename,engine = 'xlsxwriter')
        outputDF.to_excel(ExcelWriter,sheet_name=oldanalyst,index=False)
        workbook = ExcelWriter.book
        worksheet1 = ExcelWriter.sheets[oldanalyst]
        format2 = workbook.add_format({'num_format': '0.00%'})
        worksheet1.set_column('A:C',22)
        worksheet1.set_column('D:D',22,frmat2)
        worksheet1.set_column('I:I',format2)
        #(row,column 0 based index)
        #worksheet1.freeze_panes(1,3)
        ExcelWriter.save()
        
        #Clear dataframe
        outputDF = outputDF[0:0]
        
  
        #Set oldanalyst = Analyst
        oldanalyst = Analyst
    
        
    #append to outputDF. Just give values to columns with data,othwise it will be blank.
    outputDF = outputDF.append({'INDEX NAME':Index,'PROFORMA INDEX 
    SHARES':Shares,ignore_index=True)

    #print(rowcount)   

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)