新的改变
我的开篇博客给出了需要更多手动操作的简化版:
续篇的重要改进主要有:采用了函数的形式,便于参数的输入以及反复调用;
自动获取指定目录文件,检索输出文件目录,轻松实现批量化提取;
考虑到不同公司财务报表第一行标题的差异,建立了一个集合用于判断;
由于知识水平和时间的局限,未能有效实现多进程优化。
新的改变
在之后的文章里,将会上传提供一系列财务分析指标,企业估值,资本成本计算等一站式服务的Excel模板以及相应数据录入和处理的代码。
"""TabFromDocx
上市公司财务报表提取
"""
import os
import docx as d
import openpyxl as o
def TabFromDocx(file,output_path='/media/huangzefang/6982-9D43/IO/IO2'):
tle=['合并资产负债表','母公司资产负债表','合并利润表','母公司利润表','合并现金流量表','母公司现金流量表']
Set={'附注','期末余额','本期发生额','本期金额','期初余额','年初余额','上期发生额','上期金额'}
print('正在处理: ', file)
outcome=os.path.splitext(file)[0]+'.xlsx'
done=set(os.listdir(output_path))
if outcome in done:
print('已存在: ',os.path.splitext(file)[0]+'.xlsx')
return
mywb = o.Workbook()
mysheet=mywb["Sheet"]
i=-1
doc=d.Document(file)#读入文件
tabs=doc.tables#获取文件中的表格集
k=0
K=0#大写行数在后续进程中没有被重置
flag=0 #写入表格的开关标志
count=-1#六张报表打完以后剩下和附注一起放sheet里面
Flag=1#是否开启检测(主要是为了在六张表打完以后把工作表切换成sheet)
for tab in tabs[:]:
rows=tab.rows
for row in rows[:]: # 读每行
j=64
k+=1
cells=row.cells
if cells[0].text.find('项目')!=-1 and Flag==1:#第一个标志'项目'在权益变动表和其他各处都有出现,权益表比较特殊还有换行符所以用find
logic=True
for check in range(0,len(cells)): #
if len(cells)<2 or (cells[check].text not in Set): #可能有"附注"列,但所有报表形式不会只有两列#满足此条件的只有六张表和附注
logic=False
break
if logic :
flag=1
i+=1
count+=1
if count!=6:
mywb.create_sheet(index=i,title=tle[i])
mysheet = mywb.get_sheet_by_name(tle[i])
else:
mywb.create_sheet(index=i,title='附注')
mysheet = mywb.get_sheet_by_name('附注')
Flag=0
k=0
else:
flag=0
if Flag==1:
if flag==1 :
k+=1
for cell in cells[:]: # 读一行中的所有单元格
j+=1
c = cell.text
tmp=chr(j)+str(k)
mysheet[tmp] = c
else:
K+=1 #大写的行数没有重置过,最后是权益变动表
for cell in cells[:]: # 读一行中的所有单元格
j+=1
c = cell.text
tmp=chr(j)+str(K)
mysheet[tmp] = c
else:
k+=1
for cell in cells[:]: # 读一行中的所有单元格
j+=1
c = cell.text
tmp=chr(j)+str(k)
mysheet[tmp] = c
mywb.save(output_path+'/'+outcome)
print('完成: ',os.path.splitext(file)[0]+'.xlsx')
def tfd(input_path='/media/huangzefang/6982-9D43/IO/IO1',output_path='/media/huangzefang/6982-9D43/IO/IO2'):
os.chdir(input_path)
for file in os.listdir():
if os.path.splitext(file)[1]=='.docx':
TabFromDocx(file, output_path)