1.代码介绍
本代码的主要功能是通过弹窗传入一个文件夹路径(文件夹下存放pdf版本的增值税电子发票),然后就会解析文件夹下所有的发票,然后把提取后的信息写入到Excel中,最后Excel会保存在python文件的当前目录。
1.1 需要用到的python库
文章来源:https://www.toymoban.com/news/detail-730524.html
import os
import re
import logging
import tkinter as tk
from tkinter import filedialog
from datetime import datetime
import pdfplumber
import pandas as pd
from logging.handlers import RotatingFileHandler
# 提取发票信息
class ExtraInfo():
def __init__(self) -> None:
# 通过logger设置日志格式
logger = logging.getLogger()
logger.setLevel("INFO")
fh = RotatingFileHandler("run.log", maxBytes=1024*1024, backupCount=1, encoding="utf-8") # <这里设置了日志最大只能为1M>, <备份数设为1, 如果不设则maxBytes不生效>, <输出到文件>
sh = logging.StreamHandler() # <输出到控制台>
fh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s"))
sh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s"))
logger.addHandler(fh) # <使fh生效>
# logger.addHandler(sh) # <使sh生效>
self.logger = logger
@staticmethod
def extra_invoice_info(file_path):
text = ""
try:
with pdfplumber.open(file_path) as pdf:
page = pdf.pages[0]
text = page.extract_text()
except Exception as e:
print(f"出现异常:{file_path}-{e}")
finally:
return text
def analyze_invoice_info(self, pdf_dir):
ls_dir = os.listdir(pdf_dir)
ls_data = []
for i in ls_dir:
pdf_path = os.path.join(pdf_dir, i)
if pdf_path.endswith(".pdf"):
try:
text = self.extra_invoice_info(pdf_path)
mtime = os.path.getmtime(pdf_path) #修改时间
文件修改时间 = datetime.fromtimestamp(int(mtime))
名称 = re.findall(r"名\s{0,1}称\s{0,1}[:,:]\s{0,1}(.*?)\s", text, re.I|re.S)
识别号 = re.findall(r"纳税人识别号[:, :]\s{0,1}(.*?)\s", text, re.I|re.S)
开票项目名称 = re.findall(r"税\s{0,1}额\s{0,1}(.*?)\s", text, re.I|re.S)
开票日期 = re.findall(r"开票日期\s{0,1}[:,:]\s{0,1}(.*?)日", text, re.I|re.S)
发票号码 = re.findall(r"发票号码\s{0,1}[:,:]\s{0,1}(.*?)\s", text, re.I|re.S)
价税合计 = re.findall(r".小写.[\s]{0,1}[\xa5,¥]\s{0,1}(.*?)\s", text, re.I|re.S)
if not 价税合计:
价税合计 = re.findall(r"小写\(cid:61\)[\xa5,¥]\s{0,1}(.*?)\s", text, re.I|re.S)
if not 价税合计:
价税合计 = re.findall(r"大写.\s{0,1}(.*?)\s", text, re.I|re.S)
ret = [pdf_path, 文件修改时间, 名称[0], 名称[1], 识别号[0], 识别号[1], 开票项目名称[0], 开票日期[0].replace(" ", "")+"日", f"'{发票号码[0]}", f"'{价税合计[0]}"]
ret = [str(k).replace(" ", "").replace("'", "") for k in ret]
except Exception as e:
self.logger.warning(e)
self.logger.warning([text])
ret = [pdf_path, 文件修改时间, "", "", "", "", "", "", "", ""]
finally:
self.logger.warning([text])
self.logger.info(ret)
ls_data.append(ret)
return ls_data
def to_excel(self, save_path, pdf_dir):
ls_data = self.analyze_invoice_info(pdf_dir)
df = pd.DataFrame(ls_data, columns=["文件路径", "文件修改时间", "购方名称", "销方名称", "购方识别号", "销方识别号", "开票项目名称" , "开票日期", "发票号码", "价税合计"])
writer = pd.ExcelWriter(save_path, engine='openpyxl')
df.to_excel(writer, sheet_name='Sheet1', startrow=0, startcol=0, index=False)
writer.save() # 如果writer.save()报错, 可能是你的pandas版本比较高, 请改为writer._save()或者writer.close()
# 弹窗获取文件夹
class PopUp():
def __init__(self) -> None:
self.folder_path = ""
self.root = tk.Tk()
self.folder_label = tk.Label(self.root, text="请选择文件夹")
self.folder_label.pack(padx=5, pady=5)
def browse_folder(self):
self.folder_path = filedialog.askdirectory()
print(self.folder_path)
if self.folder_path:
self.folder_label.config(text=self.folder_path)
def pop_up(self):
self.root.title("上传文件夹")
self.root.geometry("300x150")
browse_button = tk.Button(self.root, text="浏览", command=self.browse_folder)
browse_button.pack(padx=5, pady=5)
upload_button = tk.Button(self.root, text="提交", command=self.root.destroy)
upload_button.pack(padx=5, pady=5)
self.root.mainloop()
return self.folder_path
if __name__ == '__main__':
pop = PopUp()
dir = pop.pop_up()
extra = ExtraInfo()
save_path = r"ouput.xlsx" # 可以自行修改保存路径
extra.to_excel(save_path, dir)
2.运行过程截图
2.1弹窗:点击“浏览”选择文件夹路径,然后点击“提交”即可!
2.2 生成的Excel
2.3 提取的效果
文章来源地址https://www.toymoban.com/news/detail-730524.html
到了这里,关于python 提取增值税电子发票信息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!