Python处理Excel(6):处理清产核资表格
openpyxl能保持Excel表原有的格式。
一、复制应收款

#coding=utf-8
#复制粘贴应收款
import xlrd, xlwt, xlwings, pyautogui, time, pyperclip, easygui, os, tkinter, io,pandas,shutil,re, os
from tkinter import filedialog,ttk
from openpyxl import load_workbook    #pip install openpyxl
from openpyxl.styles import Border, Side, colors
#import autopy as at#file= tkinter.filedialog.askopenfile()#选择打开什么文件,返回IO流对象
#file= tkinter.filedialog.askopenfilename()#选择打开什么文件,返回文件名#print(file)from io import StringIO
import sys
from contextlib import contextmanager
import syscurn_path = os.getcwd() #current path当前路径
temp_tabl_path = os.path.join(curn_path, 'Template Table')
outp_tabl_path = os.path.join(curn_path, 'Output Table')
data_sour_path = os.path.join(curn_path, 'Data Source')
#print(temp_tabl_path)
df = pandas.read_excel('贝佳电脑端账套号 所有经济组织按账套号排序 改标准名后.xlsx', dtype=str)accnt_dict2 = dict(zip(df['单位简称1'],df['三位数账套号'] )) #字典格式是'八家经济联合社':'044'
#totl = 0 #不加这个报错UnboundLocalError: local variable 'totl' referenced before assignment
#print(accnt_dict2)
# easygui.msgbox(msg='请选择数据源文件夹。')
# print('选择目录,返回目录名')
# raw_folder_path=tkinter.filedialog.askdirectory()
# #raw_folder_path = r'd:\贝佳会计系统导出数据\两项经费统计\2020序时簿'
# #easygui.msgbox(msg='请选择Excel模板(目标Excel表或数据写入Excel表)。')
# easygui.msgbox(msg='请选择写入的Excel文件。')
# targ_file_path =easygui.fileopenbox(msg='请选择Excel模板(目标Excel表或数据写入Excel表)。')#targ_file_path = targ_file_path.replace(' 模板.xls', '.xls').replace(' 模板.xlsx', '.xlsx')# fil_nam = ''
# raw_file_path = ''
# targ_file_path = ''# # 判断是否存在output文件夹
# OutputPath = r"E:\MyProjects\PycharmProjects\python01\Python And Excel\Asset and Capital Verification"
# # if (os.path.exists(OutputPath)):
# #     shutil.rmtree(OutputPath)
# #     print('output dir has been rm -rf and new makedirs')
# # os.makedirs(OutputPath)
# if not os.path.exists(OutputPath):
#     os.mkdir(OutputPath)
#     #print('覆盖Excel原来的数据写入Excel')
#     # 写入文件保存在output 文件夹下
#     #filepath = os.path.join(OutputPath, '村(社区)办公经费.xls')
#     #targ_data.to_excel(filepath, header=3, index=False, encoding='utf-8', sheet_name='村(社区)办公经费')def get_file_list(raw_folder_path):# 打开文件dirs = os.listdir(raw_folder_path)raw_file_list=[]raw_file_path_list=[]for home, dirs, files in os.walk(raw_folder_path):for file_name in files:raw_file_list.append((file_name))raw_file_path_list.append(os.path.join(home, file_name))#print('raw_file_list')#print(raw_file_list)return raw_file_list,raw_file_path_listdef gath_data(raw_file_path, targ_file_path):#global totl #要定义全局变量star_row = 9shet_name = 'Sheet1'wb_raw = load_workbook(raw_file_path)ws_raw = wb_raw[shet_name]row_raw = ws_raw.max_rowcolm_raw = ws_raw.max_columnlist_accn_name , list_init_baln , list_end_baln , list_vari_quan =[],[],[],[]if ws_raw.cell(row=3, column=1).value == '应收款':totl = float(ws_raw.cell(row=3, column=5).value)  # total amount总额else:totl = 0for r in range(3,row_raw):accn_name = ws_raw.cell(row=r, column=1).value   # account name科目名称init_baln = float(ws_raw.cell(row=r, column=5).value)  # initial balance期初余额end_baln = float(ws_raw.cell(row=r, column=12).value)  # ending balance期末余额vari_quan = float(ws_raw.cell(row=r, column=6).value) #variable quantity变化量if accn_name =='应收款':passif accn_name[:3] == '   ' and accn_name[4:4] != ' ':#if accn_name[:3] == '   ' and accn_name[:6] == '      ':passif accn_name[:6] =='      ':accn_name = accn_name.strip()#print(accn_name)list_accn_name.append(accn_name)list_init_baln.append(init_baln)print(list_accn_name)print(list_init_baln)wb_raw.save(raw_file_path)# 释放资源,不然脚本无法打开,会处于锁定状态。wb_raw.close()shet_name = '应收款项清查登记表'wb_targ = load_workbook(targ_file_path)ws_targ = wb_targ[shet_name]row_targ = ws_targ.max_rowcolm_targ = ws_targ.max_column#print(row)#print(colm)# print(list_accn_name)# print(list_init_baln)for a in range(len(list_accn_name)):ws_targ.cell(row=star_row, column=2).value = list_accn_name[a]for colm in [6, 9, 11]:ws_targ.cell(row=star_row, column=colm).value = list_init_baln[a]#print('在第{}行写入:{},{}。'.format(star_row, list_accn_name[a], list_init_baln[a]))star_row+=1#for foot in ['相关事项说明:', '清产核资工作小组负责人(签章):','填表人:','打印日期:']:ws_targ.cell(row=row_targ, column=1).value = '相关事项说明:'ws_targ.cell(row=row_targ, column=4).value = '清产核资工作小组负责人(签章):'ws_targ.cell(row=row_targ, column=7).value = '填表人:'ws_targ.cell(row=row_targ, column=9).value = '打印日期:'wb_targ.save(targ_file_path)wb_targ.close()return list_accn_name, list_init_baln, totl# wb_targ.save(targ_file_path)# # 释放资源,不然脚本无法打开,会处于锁定状态。# wb_targ.close()# # 没有engine='openpyxl会报错# #合并单元格不能将数值转化为浮点型,所以要去除表头和表脚。header=3, skipfooter=1# getInfo = pandas.read_excel(raw_file_path, sheet_name="Sheet1", header=3, skipfooter=1, keep_default_na=False, engine='openpyxl')## print('不覆盖Excel原来的数据写入Excel:{}'.format(targ_file_path))# book = load_workbook(targ_file_path)# writer = pandas.ExcelWriter(targ_file_path, engine='openpyxl')# writer.book = book# writer.sheets = dict((ws.title, ws) for ws in book.worksheets)  # 获取文件中已存在的表名,这行直接用,不用修改# for i in getInfo.index:#     iden = getInfo.loc[i].values[0] # 固定资产编号identifier#     # print(iden)#     # print(type(iden)) #<class 'numpy.int64'>#     # print(type(str(iden))) #string#     # print(str(iden))#     # if str(iden) =='001':#     #     print(iden)#     # #     break#     # if iden == 1:#     #     print(iden)#     #     break#     if int(iden) ==1 or iden == 2 or iden == 3 or iden == 4 or iden == 5 or iden == 6 or iden == 7:#     #if str(iden) =='001' or iden == '002' or iden == '003' or iden == '004' or iden == '005' or iden == '006' or iden == '007':#     #if str(iden) == ('001' or '002' or '003' or  '004' or '005' or '006' or '007'):#     #if int(iden) == (1 or 2 or 3 or 4 or 5 or 6 or 7):#         print(iden)#         pass#     else:#         accn_name = getInfo.loc[i].values[1] # account name科目名称#         accm_depr = getInfo.loc[i].values[3]#accumulated depreciation 累计折旧#         init_baln = getInfo.loc[i].values[2]#initial balance期初余额#         end_baln = getInfo.loc[i].values[4]  # 期末余额ending balance#         # if accn_code[:2] =='112': #如果科目代号前面的三位数是112应收款。#         #     #for j in range(len(getInfo.loc[i].values)):#         accm_depr_seri = pandas.Series(init_baln, dtype=float)#         init_baln_seri = pandas.Series(init_baln, dtype=float)#         end_baln_seri = pandas.Series(end_baln, dtype=float)  # 期末余额转化为浮点型。#         # end_baln_seri = pandas.Series(end_baln) #依然为常规格式,数值能求和。#         #print(end_baln_seri)#         #print('写入: {} {} {} {}'.format(accn_name, init_baln, accm_depr, end_baln))#         # 写入  固定资产清查登记表-2(非经营性固定资产)从第12行,第2列写入,工作表名前有空格,在Excel表上看不出来#         pandas.Series(star_row-10).to_excel(writer, header=False, index=False, startrow=star_row, startcol=0,#                                        merge_cells=True,#                                        sheet_name=' 固定资产清查登记表-2')  # 编号#         pandas.Series('机器设备').to_excel(writer, header=False, index=False, startrow=star_row, startcol=1,merge_cells=True,#                                    sheet_name=' 固定资产清查登记表-2') #类别#         pandas.Series(accn_name).to_excel(writer, header=False, index=False, startrow=star_row, startcol=2,merge_cells=True,#                                    sheet_name=' 固定资产清查登记表-2') #名称#         #pandas.Series('机器设备').to_excel(writer, header=False, index=False, startrow=11, startcol=1, sheet_name=' 固定资产清查登记表-2') #类别#         init_baln_seri.to_excel(writer, header=False, index=False, startrow=star_row, startcol=10,#                                    sheet_name=' 固定资产清查登记表-2')#         init_baln_seri.to_excel(writer, header=False, index=False, startrow=star_row, startcol=19,#                                    sheet_name=' 固定资产清查登记表-2')#         accm_depr_seri.to_excel(writer, header=False, index=False, startrow=star_row, startcol=11,#                                    sheet_name=' 固定资产清查登记表-2')#         accm_depr_seri.to_excel(writer, header=False, index=False, startrow=star_row, startcol=20,#                                    sheet_name=' 固定资产清查登记表-2')#         end_baln_seri.to_excel(writer, header=False, index=False, startrow=star_row, startcol=12,#                                    sheet_name=' 固定资产清查登记表-2')#         end_baln_seri.to_excel(writer, header=False, index=False, startrow=star_row, startcol=21,#                                    sheet_name=' 固定资产清查登记表-2')#核实数中净值#         end_baln_seri.to_excel(writer, header=False, index=False, startrow=star_row, startcol=26,#                                    sheet_name=' 固定资产清查登记表-2') #去年核实数#         star_row += 1#         #print('写入到第{}行。'.format(star_row))### writer.save()# #不添加writer.close()会损坏Excel,报错zipfile.BadZipFile: File is not a zip file# writer.close()#                 # row_data=getInfo.loc[i].values#                 # print(row_data)#                 # row_data_list=list(row_data)def func():#row_resu = 4raw_file_list,raw_file_path_list =get_file_list(data_sour_path)print(1)#print(raw_file_list)temp_file_list, temp_file_path_list = get_file_list(temp_tabl_path)#模板文件夹template table的文件复制到output table文件夹下outp_tabl_list = []for i in range(len(temp_file_list)):outp_file_path =os.path.join(outp_tabl_path, temp_file_list[i])shutil.copy(temp_file_path_list[i], outp_file_path)outp_file_list, outp_file_path_list = get_file_list(outp_tabl_path)print(outp_file_path_list)print('gather data to excel')for i in range(0,len(outp_file_path_list)):print(f'尝试第{i + 1}个文件读写。')outp_fil_nam = outp_file_list[i]orgz = outp_fil_nam.replace('.xlsx','').replace('台山市冲蒌镇','') #organization组织单位#print(orgz)list_tabl_accn_disc = ['资产负债表', '收益分配表', '应收款', '应付款', '固定资产明细表', '在建工程明细表']tabl_type = '应收款'if orgz in accnt_dict2.keys():   #前锋村升平经济合作社不在字典里,就会主键报错KeyErroraccnt_Num = accnt_dict2[orgz]raw_file = '2021 {}{}{}.xlsx'.format(accnt_Num,orgz,tabl_type) #构造文件名,如2021 044八家经济联合社固定资产明细表.xlsprint(accnt_Num, orgz)raw_file_path = os.path.join(data_sour_path, raw_file)if os.path.exists(raw_file_path):#print(raw_file_path)# targ_file_path = os.path.join(outp_tabl_path, '{}.xlsx'.format(orgz))# print(targ_file_path)# raw_file_path = raw_file_path_list[i]#print(raw_file_path)#input_file_path_plan = r"E:\贝佳会计系统导出数据\两项经费统计\2020年序时簿\2020 045冲洋经联社序时簿.xls"#modf_excl(targ_file_path=outp_file_path_list[i])#row_inse(file_path= outp_file_path_list[i])list_accn_name, list_init_baln, totl = gath_data(raw_file_path =raw_file_path, targ_file_path = outp_file_path_list[i])resu_file_path = r'2021年度清产核资填写数据情况表.xlsx'wb_resu = load_workbook(resu_file_path) #workbook resultws_resu = wb_resu['Sheet1']for row_resu in range(4, 232):# print(accnt_Num)# print(str(ws_resu.cell(row=row_resu, column=2).value))if str(ws_resu.cell(row=row_resu, column=2).value) == str(accnt_Num):  # 都是stringws_resu.cell(row=row_resu, column=5).value = 1ws_resu.cell(row=row_resu, column=15).value = totl #应收款总额wb_resu.save(resu_file_path)wb_resu.close()# writer.save()# writer.close()# book.save('新建 Microsoft Excel 工作表.xlsx')# book.close()
if __name__ == "__main__":func()#
#
#
#
#
#
#
#
#
#
# def saveAsNewExcelFile(raw_file_path_list):
#     list1=[]
#     print("file name")
#     fil_nam='村委会1'
#
#     for raw_file_path in raw_file_path_list:
#
#         for i in getInfo.index:
#             for j in range(len(getInfo.loc[i].values)):
#                 if (getInfo.loc[i].values[j] == '专项应付款-村(社区)办公经费'):
#                     start_col = i + 1
#                     row_data = getInfo.loc[i].values
#                     # print(row_data)
#                     row_data = list(row_data)
#                     row_data = list[fil_nam] + row_data
#                     list1.append(row_data)
#         print(list1)
#         print('target data目标数据')
#         targ_data = pandas.DataFrame(list1)
#
#
#
#
#     # get cared macro info from testplan and save as 'MacroInfo.xlsx'
#     getInfo = pandas.read_excel(input_file_path_plan, sheet_name="Sheet1", dtype=str, keep_default_na=False)
#     for i in getInfo.index:
#         for j in range(len(getInfo.loc[i].values)):
#             if (getInfo.loc[i].values[j] == '专项应付款-村(社区)办公经费'):
#                 start_col = i + 1
#                 row_data=getInfo.loc[i].values
#                 #print(row_data)
#                 row_data=list(row_data)
#                 row_data=list[fil_nam]+row_data
#                 list1.append(row_data)
#     print(list1)
#     print('target data目标数据')
#     targ_data=pandas.DataFrame(list1)
#                 #break #add 2.3
#                 # print(getInfo.loc[i].values[j])
#     #x = pandas.DataFrame(getInfo.iloc[start_col:, ])
#     #print(x)
#     # 判断是否存在output文件夹
#     OutputPath=r"e:\贝佳会计系统导出数据\两项经费统计"
#     if (os.path.exists(OutputPath)):
#         shutil.rmtree(OutputPath)
#         print('output dir has been rm -rf and new makedirs')
#     os.makedirs(OutputPath)
#
#     # 写入文件保存在output 文件夹下
#     filepath = os.path.join(OutputPath, '村(社区)办公经费.xls')
#     targ_data.to_excel(filepath, header=2, index=False, encoding='utf-8', sheet_name='村(社区)办公经费')

二、复制粘贴固定资产去年核实数等

#coding=utf-8
#复制粘贴固定资产去年核实数等
import xlrd, xlwt, xlwings, pyautogui, time, pyperclip, easygui, os, tkinter, io,pandas,shutil,re, os
from tkinter import filedialog,ttk
from openpyxl import load_workbook    #pip install openpyxl
from openpyxl.styles import Border, Side, colors
#import autopy as at
import datetime#file= tkinter.filedialog.askopenfile()#选择打开什么文件,返回IO流对象
#file= tkinter.filedialog.askopenfilename()#选择打开什么文件,返回文件名#print(file)from io import StringIO
import sys
from contextlib import contextmanager
import syscurn_path = os.getcwd() #current path当前路径
temp_tabl_path = os.path.join(curn_path, 'Template Table')
outp_tabl_path = os.path.join(curn_path, 'Output Table')
data_sour_path = os.path.join(curn_path, 'Data Source')
#print(temp_tabl_path)
df = pandas.read_excel('贝佳电脑端账套号 所有经济组织按账套号排序 改标准名后.xlsx', dtype=str)accnt_dict2 = dict(zip(df['单位简称1'],df['三位数账套号'] )) #字典格式是'八家经济联合社':'044'def get_file_list(raw_folder_path):# 打开文件dirs = os.listdir(raw_folder_path)raw_file_list=[]raw_file_path_list=[]for home, dirs, files in os.walk(raw_folder_path):for file_name in files:raw_file_list.append((file_name))raw_file_path_list.append(os.path.join(home, file_name))#print('raw_file_list')#print(raw_file_list)return raw_file_list,raw_file_path_listdef gath_data(raw_file_path, targ_file_path):shet_name = ' 固定资产清查登记表-2'wb_raw = load_workbook(raw_file_path)ws_raw = wb_raw[shet_name]row_raw = ws_raw.max_rowlist_accn_name = [] #account name科目名称list_veri_amou = [] #Verify the amount核实数list_leibie = [] #类别list_goujian_shijian = [] #构建时间for r in range(12,row_raw):accn_name = ws_raw.cell(row=r, column=3).value   # account name科目名称if accn_name =='' or accn_name == None:breakelse:try:leibie = ws_raw.cell(row=r, column=2).valuegoujian_shijian = ws_raw.cell(row=r, column=4).valueveri_amou = float(ws_raw.cell(row=r, column=22).value)  # float容易报错,放在后面,去年核实数是去年净值数# veri_amou = round(float(ws_raw.cell(row=r, column=14).value),2)except:veri_amou = ''list_accn_name.append(accn_name)list_veri_amou.append(veri_amou)list_leibie.append(leibie)list_goujian_shijian.append(goujian_shijian)# dict_raw = dict(zip(list_accn_name, list_veri_amou))# print(dict_raw)print(list_accn_name)print(list_veri_amou)wb_raw.save(raw_file_path)# 释放资源,不然脚本无法打开,会处于锁定状态。wb_raw.close()wb_targ = load_workbook(targ_file_path)ws_targ = wb_targ[shet_name]row_targ = ws_targ.max_rowfor r in range(10, row_targ+1):if ws_targ.cell(row=r, column=1).value == '相关事项说明:':#print('相关事项说明在第{}行.'.format(r))breakrow_targ = r#print(row_targ)# # #方法1:双重遍历,遍历行,遍历列表。for r in range(12, row_targ-1):accn_name_targ = ws_targ.cell(row=r, column=3).value #account name targetws_targ.cell(row=r, column=26).value = '1' #去年数量shuliang_qunianws_targ.cell(row=r, column=24).value = '否'#是否为扶贫资产fupin_zichan_or_not#veri_amou_targ = ws_targ.cell(row=r, column=11).valueif accn_name_targ == None or accn_name_targ == '': #不是if accn_name_targ == ''breakelse:for i in range(len(list_accn_name)):if accn_name_targ == list_accn_name[i]:ws_targ.cell(row=r, column=27).value = list_veri_amou[i]ws_targ.cell(row=r, column=2).value = list_leibie[i]ws_targ.cell(row=r, column=4).value = list_goujian_shijian[i]print('相同', r, i, accn_name_targ, list_veri_amou[i])break #双重遍历一定要加break,不然全部运行else的语句。else:ws_targ.cell(row=r, column=12).value = 0.00#print(i, r, list_accn_name[i], accn_name_targ)# #方法2:方法1:双重遍历,遍历行,遍历列表。# for r in range(9, row_targ-1):#     accn_name_targ = ws_targ.cell(row=r, column=2).value #account name target#     if accn_name_targ == None or accn_name_targ == '': #不是if accn_name_targ == ''#         break#     else:#         for key, value in dict_raw.items():#             if accn_name_targ == key:#                 ws_targ.cell(row=r, column=16).value = value#                 print('相同', r, key, accn_name_targ, value)#                 break #双重遍历一定要加break,不然全部运行else的语句。#             else:#                 ws_targ.cell(row=r, column=11).value = 0.00#                 #print('不相同')# for key, value in dict_raw.items():#     print("\nKey :" + str(key))#     print("Value: " + str(value))# for i in range(len(list_accn_name)):#     for r in range(9, row_targ):#         accn_name_targ = ws_targ.cell(row=r, column=2).value  # account name target#         if accn_name_targ == list_accn_name[i]:#             ws_targ.cell(row=r, column=11).value = list_veri_amou[i]#             print(i, r, accn_name_targ, list_veri_amou[i])#             break#         else:#             ws_targ.cell(row=r, column=11).value = 0.00wb_targ.save(targ_file_path)wb_targ.close()def func():#row_resu = 4raw_file_list,raw_file_path_list =get_file_list(data_sour_path)#print(raw_file_list)temp_file_list, temp_file_path_list = get_file_list(temp_tabl_path)#模板文件夹template table的文件复制到output table文件夹下outp_tabl_list = []for i in range(len(temp_file_list)):outp_file_path =os.path.join(outp_tabl_path, temp_file_list[i])shutil.copy(temp_file_path_list[i], outp_file_path)outp_file_list, outp_file_path_list = get_file_list(outp_tabl_path)print(outp_file_path_list)print('gather data to excel')for i in range(0,len(outp_file_path_list)):print(f'尝试第{i + 1}个文件读写。')outp_fil_nam = outp_file_list[i]orgz = outp_fil_nam.replace('.xlsx','').replace('台山市冲蒌镇','') #organization组织单位#print(orgz)if orgz in accnt_dict2.keys():   #前锋村升平经济合作社不在字典里,就会主键报错KeyErroraccnt_Num = accnt_dict2[orgz]raw_file = outp_fil_namprint(accnt_Num, orgz)raw_file_path = os.path.join(data_sour_path, raw_file)if os.path.exists(raw_file_path):gath_data(raw_file_path =raw_file_path, targ_file_path = outp_file_path_list[i])resu_file_path = r'2021年度清产核资填写数据情况表.xlsx'wb_resu = load_workbook(resu_file_path) #workbook resultws_resu = wb_resu['Sheet1']for row_resu in range(4, 232): #4+228=232,所有的经济组织的行# print(accnt_Num)# print(str(ws_resu.cell(row=row_resu, column=2).value))if str(ws_resu.cell(row=row_resu, column=2).value) == str(accnt_Num):  # 都是stringws_resu.cell(row=row_resu, column=36).value = 1wb_resu.save(resu_file_path)wb_resu.close()if __name__ == "__main__":func()

三、Asset and Capital Verification 收益分配表从收支明细表读取数据

#coding=utf-8
#复制粘贴财务公开收益分配表
import xlrd, xlwt, xlwings, pyautogui, time, pyperclip, easygui, os, tkinter, io,pandas,shutil,re, os
from tkinter import filedialog,ttk
from openpyxl import load_workbook    #pip install openpyxl
from openpyxl.styles import Border, Side, colors
#import autopy as at#file= tkinter.filedialog.askopenfile()#选择打开什么文件,返回IO流对象
#file= tkinter.filedialog.askopenfilename()#选择打开什么文件,返回文件名#print(file)from io import StringIO
import sys
from contextlib import contextmanager
import syscurn_path = os.getcwd() #current path当前路径
temp_tabl_path = os.path.join(curn_path, 'Template Table')
outp_tabl_path = os.path.join(curn_path, 'Output Table')
data_sour_path = os.path.join(curn_path, 'Data Source')
#print(temp_tabl_path)
df = pandas.read_excel('贝佳电脑端账套号 所有经济组织按账套号排序 改标准名后.xlsx', dtype=str)
accnt_dict2 = dict(zip(df['单位简称1'],df['三位数账套号'] )) #字典格式是'八家经济联合社':'044'def get_file_list(raw_folder_path):# 打开文件dirs = os.listdir(raw_folder_path)raw_file_list=[]raw_file_path_list=[]for home, dirs, files in os.walk(raw_folder_path):for file_name in files:raw_file_list.append((file_name))raw_file_path_list.append(os.path.join(home, file_name))#print('raw_file_list')#print(raw_file_list)return raw_file_list,raw_file_path_listdef gath_data(raw_file_path, targ_file_path):star_row = 9shet_name = 'Sheet1'wb_raw = load_workbook(raw_file_path)ws_raw = wb_raw[shet_name]row_raw = ws_raw.max_rowjingying_shouru = 0.0000 #经营收入fabao_ji_shangjiao_shouru = 0.0000 #发包及上交收入touzi_shouyi = 0.0000 #投资收益nongyeshui_fanhuan = 0.0000 #农业税返还buzhu_shouru = 0.0000 #补助收入qita_shouru = 0.0000 #其他收入fulifei_shouru = 0.0000 #福利费收入jingying_zhichu = 0.0000  # 经营支出guanlifei_zhichu = 0.0000 #管理费支出ganbu_baochou = 0.0000  # 干部报酬shubaofei = 0.0000 #书报费qita_zhichu = 0.0000 #其他支出fulifei_zhichu = 0.0000  # 福利费支出fenpeinonghu_ji_touzizhe = 0.0000 #分配农户及投资者gudingzichan_goujian = 0.0000 #固定资产构建#因为零值为0,不是空白,所以都可以转浮点型。for r in range(3,row_raw):inco_item = ws_raw.cell(row=r, column=2).value #income item收入项目inco_valu = float(ws_raw.cell(row=r, column=4).value)#round()函数比较迷,它不完全是按照四舍五入的原则来进位的,因此不建议大家使用。# 它的保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则会保留到偶数的一边。好了笔者也要绕晕了,反正笔者是不会用这种方法的。#inco_valu = round(inco_valu/10000,4) #以万元为单位,保留4位小数#print(inco_valu)inco_valu = float('%.4f' % (inco_valu/10000)) #以万元为单位,保留4位小数#print(inco_valu)if inco_item =='一、经营收入                  ':jingying_shouru = inco_valuif inco_item == '二、发包及上交收入            ':fabao_ji_shangjiao_shouru = inco_valuif inco_item == '三、投资收益                  ':touzi_shouyi = inco_valuif inco_item == '四、农业税附加返还收入        ':nongyeshui_fanhuan = inco_valuif inco_item == '五、补助收入                  ':buzhu_shouru =inco_valuif inco_item == '六、其他收入                  ':qita_shouru = inco_valuif inco_item == '七、福利费收入                ':fulifei_shouru =inco_valuexpe_item = ws_raw.cell(row=r, column=5).value #expend item支出项目expe_valu = float(ws_raw.cell(row=r, column=7).value) #expend value#expe_valu = round(expe_valu/10000,4) #以万元为单位,保留4位小数expe_valu = float('%.4f' % (expe_valu / 10000)) # 以万元为单位,保留4位小数if expe_item == '一、经营支出                  ':jingying_zhichu = expe_valuif expe_item == '二、管理费支出                ':guanlifei_zhichu = expe_valuif expe_item == '      干部报酬                    ' or expe_item == '      干部报酬                    ':ganbu_baochou = expe_valuif expe_item == '      书报费                      ' or expe_item == '      书刊费                      ':shubaofei = expe_valuif expe_item == '三、其他支出                  ':qita_zhichu = expe_valuif expe_item == '、福利费支出                ':fulifei_zhichu = expe_valuif expe_item == '五、分配农户及投资者          ':fenpeinonghu_ji_touzizhe = expe_valuif expe_item == '六、固定资产购建              ':gudingzichan_goujian = expe_valu#清产核资表格中的其他收入qita_shouru_qingchanhezi = nongyeshui_fanhuan + qita_shouru + fulifei_shouru#total income总收入totl_inco = jingying_shouru + fabao_ji_shangjiao_shouru +touzi_shouyi + buzhu_shouru +qita_shouru_qingchanhezi# 清产核资表格中的其他收支出qita_zhichu_qingchanhezi = qita_zhichu + fulifei_zhichu + fenpeinonghu_ji_touzizhe + gudingzichan_goujiantotl_expe = jingying_zhichu + guanlifei_zhichu + qita_zhichu_qingchanheziwb_raw.save(raw_file_path)# 释放资源,不然脚本无法打开,会处于锁定状态。wb_raw.close()shet_name = '收益分配统计表'wb_targ = load_workbook(targ_file_path)ws_targ = wb_targ[shet_name]ws_targ.cell(row=8, column=2).value = totl_incows_targ.cell(row=8, column=3).value = jingying_shouru  #万元为单位,保留四位小数ws_targ.cell(row=8, column=4).value = fabao_ji_shangjiao_shouru #发包及上交收入ws_targ.cell(row=8, column=5).value = touzi_shouyi #投资收益ws_targ.cell(row=8, column=6).value = buzhu_shouru #补助收入ws_targ.cell(row=8, column=7).value = qita_shouru_qingchanhezi #清产核资表中的其他收入ws_targ.cell(row=8, column=8).value = totl_expe #总支出ws_targ.cell(row=8, column=9).value = jingying_zhichu #经营支出ws_targ.cell(row=8, column=10).value = guanlifei_zhichu #管理费用ws_targ.cell(row=8, column=11).value = ganbu_baochou #干部报酬ws_targ.cell(row=8, column=12).value = shubaofei #书报费、报刊费ws_targ.cell(row=8, column=13).value = qita_zhichu_qingchanhezi #清产核资表中的其他支出wb_targ.save(targ_file_path)wb_targ.close()return totl_inco, totl_expedef func():raw_file_list,raw_file_path_list =get_file_list(data_sour_path)#print(1)#print(raw_file_list)temp_file_list, temp_file_path_list = get_file_list(temp_tabl_path)#模板文件夹template table的文件复制到output table文件夹下outp_tabl_list = []for i in range(len(temp_file_list)):outp_file_path =os.path.join(outp_tabl_path, temp_file_list[i])shutil.copy(temp_file_path_list[i], outp_file_path)outp_file_list, outp_file_path_list = get_file_list(outp_tabl_path)print(outp_file_path_list)print('gather data to excel')for i in range(0,len(outp_file_path_list)):print(f'尝试第{i + 1}个文件读写。')outp_fil_nam = outp_file_list[i]orgz = outp_fil_nam.replace('.xlsx','').replace('台山市冲蒌镇','') #organization组织单位#print(orgz)list_tabl_accn_disc = ['资产负债表', '收益分配表', '应收款', '应付款', '固定资产明细表', '在建工程明细表']tabl_type = '收支明细表'if orgz in accnt_dict2.keys():   #前锋村升平经济合作社不在字典里,就会主键报错KeyErroraccnt_Num = accnt_dict2[orgz]raw_file = '2021 {}{}{}.xlsx'.format(accnt_Num, orgz, tabl_type) #构造文件名,如2021 044八家经济联合社固定资产明细表.xlsprint(accnt_Num, orgz)raw_file_path = os.path.join(data_sour_path, raw_file)if os.path.exists(raw_file_path):#totl_inco, totl_expe = gath_data(raw_file_path =raw_file_path, targ_file_path = outp_file_path_list[i])print(f'总收入、总支出分别是:{totl_inco}, {totl_expe}')print('总收入、总支出分别是:{}, {}'.format(totl_inco, totl_expe))resu_file_path = r'2021年度清产核资填写数据情况表.xlsx'wb_resu = load_workbook(resu_file_path)  # workbook resultws_resu = wb_resu['Sheet1']for row_resu in range(4, 232):if str(ws_resu.cell(row=row_resu, column=2).value) == str(accnt_Num):  # 都是stringws_resu.cell(row=row_resu, column=24).value = 1ws_resu.cell(row=row_resu, column=25).value = totl_incows_resu.cell(row=row_resu, column=26).value = totl_expewb_resu.save(resu_file_path)wb_resu.close()if __name__ == "__main__":func()

Python处理Excel(6):处理清产核资表格(1)相关推荐

  1. Python 操作 excel 插入图片、表格、设置单元格颜色、字体(三)

    Python 操作 excel 插入图片.表格.设置单元格颜色.字体 python 操作 excel 插入图片.表格.设置单元格颜色.字体 提示:以下是本篇文章正文内容,下面案例可供参考 一.open ...

  2. 基于Python处理Excel按条件合并表格

    开发环境 开发工具:PyCharm 2019.3.4 (Community Edition) Jdk:1.8+ 项目介绍 系统功能:一段python脚本 功能介绍 用python做出一个脚本对两个表格 ...

  3. python复制excel模板并保留表格样式

    需求:按照模板生成excel报表. 本地有一个模板Excel表,是xlsx格式.需要把传过来的数据,按照模板表生成新的写入数据的报表. 情况:先尝试了pandas,发现生成的新表并不会保留模板表中的样 ...

  4. python拆分excel的sheet为单文件_python拆分Excel表格并发送邮件

    工作中经常会出现需要将数据按一定的条件拆分并分发给不同的收件人的情况,今天就来给大家分享一下如何使用python拆分Excel表格并分发邮件. 以下表(2019年下半年销量数据表)数据为例: 首先我们 ...

  5. python 表格格式输出_利用python对excel中一列的时间数据更改格式操作

    问题场景:需要将下列的交期一列的数据格式更改成2019/05/10 存货编码 尺寸 数量 交期 0 K10Y0190000X B140 200 2019-05-10 00:00:00 1 K10Y01 ...

  6. pythonexcel汇总_用python汇总excel表格数据-怎样用python遍历表格中的内容

    如何用python将数据写入excel表格 # 需 xlrd-0.9.2  xlutils-1.7.1 这两个模块 from xlwt import Workbook, Formula import  ...

  7. python写表格_使用Python对Excel进行读写操作

    学习Python的过程中,我们会遇到Excel的读写问题.这时,我们可以使用xlwt模块将数据写入Excel表格中,使用xlrd模块从Excel中读取数据.下面我们介绍如何实现使用Python对Exc ...

  8. python处理excel表格教程-python操作excel(内附python教程分享)

    今天学习了下xlwings这个库,目的是为了让计算机自动化操作excel表,当某天需要做一些很繁琐的事情,就可以派上用场啦. 基本对象 网上刮来的图,很好. 大概就是xlwings中可以有多个exce ...

  9. python处理excel表格大小-如何用python处理excel表格

    前面我们已经学到了很多Python在数学领域的应用,用Python编程可以轻松解决一些数学中的常见问题.当然Python的功能应用还远远不止于此,我们的很多日常工作也可以用Python来实现.今天南京 ...

最新文章

  1. python输出去空格_python输出怎么取消空格
  2. 输入/输出延迟单元( IODELAY)简介
  3. Python最热,PyTorch增速是TF的13倍:2019数据分析/机器学习工具调查发布
  4. 我写的一个给time_t赋值的小函数
  5. Docker linux安装
  6. thinkphp如何跨模块调用方法呢?
  7. Java 判断操作系统类型(适用于各种操作系统)
  8. flyme禁止系统更新_魅族Flyme更新8.1.2.3A:重要系统更新!
  9. 关于Pac-Man,你所要了解的 一切
  10. 特斯拉造人、小鹏骑马、小米遛狗,准车企们为何集体盯上了机器人生意?
  11. 代码中大量的if/else,你有什么优化方案?
  12. PreparedStatement设置时间
  13. 六天学会BASIC语言的方法——计算机达人成长之路(10)连载
  14. 计算机右键管理没有管理员权限,鼠标右键为何没有获得管理员权限
  15. RuntimeError: Error(s) in loading state_dict for BNInception:size mismatch for
  16. 【WSN通信】基于matlab A_Star改进LEACH多跳传输协议【含Matlab源码 487期】
  17. Prometheus-监控主机基础指标配置及告警
  18. Java包(package)
  19. android关闭传感器,您如何在安卓10手机上打开和关闭传感器
  20. 中英介绍寒食节、清明节的来历及习俗

热门文章

  1. 一键清除苹果锁屏密码_苹果手机锁屏密码突然不正确了?不要慌!也先不要着急刷机!!!尝试一下以下方式!...
  2. SCons教程(7) 文件操作
  3. 一、Tensor基础
  4. 微信小程序获取数据接口动态渲染Echarts折线图
  5. 【Popper报错】Popper: modifier “undefined“ provided an invalid “fn“ property
  6. 电精2 android,安卓街机模拟器|街机电精2(街机模拟器)安卓版 - 系统天堂
  7. java加密常用的方法_JAVA MD5 加密常用 方法
  8. 2021年煤矿安全监测监控模拟试题及煤矿安全监测监控理论考试
  9. 《卓有成效的管理者》 读书摘要
  10. 一起学习CC3200系列教程之CC3200简介