当前位置:首页 > 经验 >

table表格线条怎么加上(table去掉表格的横向和竖向边框)

来源:原点资讯(www.yd166.com)时间:2022-10-29 01:17:23作者:YD166手机阅读>>

大部分公司还是需要员工自行整理发票填写报销单,并且打印电子发票后提交给财务才能报销。如果发票多了会很浪费时间,让我们用Python写个程序来管理电子发票吧。

个人发票管理功能点
  1. 发票自动识别,读取发票信息。(前期只处理PDF电子发票)
  2. 批量导出识别的发票信息。
  3. 合并多个发票文件到一个文件。

后续增加功能。会陆续写文章一步一步介绍如何实现这些功能。

  1. 提供可视化界面,支持C/S和B/S两种模式。
  2. 添加到windows任务栏。
  3. 发票分类。根据报销类型对发票进行分类标注。
  4. 发票抬头、税号、发票号等校验,排除错误抬头、避免出现重复发票。
  5. 标注已经报销的发票。
  6. 自动读取邮箱中的发票附件,并提取发票信息。
  7. 支持图片格式增值税发票。基于OCR识别发票。
  8. 支持更多其他类型的发票。
PDF格式电子发票信息读取

Python处理PDF的库很多,有PyMuPDF、PyPDF2、pdfminer、pdfplumber等,每个库都有不同的特点(这篇文章总结得比较全面,有兴趣的可以看看)。

我选择用pdfplumber(https://github.com/jsvine/pdfplumber)这个库来读取发票内容,因为它可以方便的提取PDF中的文本、图片,重要的是它可以很好地提取表格。

table表格线条怎么加上,table去掉表格的横向和竖向边框(1)

pdfplumber与其他库的比较

安装pdfplumber

pip install pdfplumber

下面的示例代码将打印出pdfplumber读取的文本信息和表格信息,并且将pdf表格和文本框保存到图片查看读取效果。另外,电子发票含有一个二维码,里面包含发票信息,pdfplumber没有办法直接解析出图片,这里使用crop()函数截取图片区域,然后再用to_image()函数转成图片。二维码图片可以用pyzbar等识别二维码的库解析,用于核对信息。

import pdfplumber with pdfplumber.open(r"1.pdf") as pdf: # 读取第一页 first_page = pdf.pages[0] # 转成图片,dpi设置为100 im = first_page.to_image(resolution=100) # 画出表格边框和线条交点 im.debug_tablefinder() # 画出文本边框 im.draw_rects(first_page.extract_words()) # 保存图片 im.save(r"1.png") # 打印读取的文本 print(first_page.extract_text()) # 打印读取的表格 print(first_page.extract_table()) # 保存pdf中的图片 for image in first_page.images: im = first_page.crop(bbox=(image['x0'],image['top'],image['x1'],image['bottom'])).to_image(resolution=100) im.save(f"{image['name']}.png")

table表格线条怎么加上,table去掉表格的横向和竖向边框(2)

表格和文本识别区域

从上图可以看出pdfplumber识别发票表格的效果还是很好的,红色线是识别的表格,蓝色圆圈点是表格线条的交点。

另外通过extract_text()打印出来的文本,我们分析可以发现,直接从文本中获取发票全部信息还是比较困难的(懒得打码就不放图了),很多信息混在一起。这个换别的库提取文本也一样,都没有很好的效果,而且不同省份的发票PDF排版还不一样,如果不通过表格区域去获取文本,是没有办法解析发票全部信息的。

最后,我们结合extract_text()extract_table()分别获取发票头和发票表格中的信息。

解析发票信息并导出到表格

解析发票比较简单,用正则表达式提取信息就可以了。以发票表格上方的发票号等信息为例,通过extract_text()获取的文本来解析(需要注意的是不同地区发票的“冒号”有的是半角有的是全角):

# 提取发票表格上方内容 invoice.number = re.search(r'发票号码(:|:)(\d )', text).group(2) invoice.date = re.search(r'开票日期(:|:)(.*)', text).group(2) Invoice.machine_number = re.search(r'机器编号(:|:)(\d )', text).group(2) invoice.code = re.search(r'发票代码(:|:)(\d )', text).group(2) invoice.check_code = re.search(r'校验码(:|:)(\d )', text).group(2)

发票表格中的内容,则通过extract_table()获取的表格内容来解析。以购买方为例,需要从指定的cell中去获取数据:

# 读取表格 table = first_page.extract_table() # 表格为4行11列 # ‘购买方’,内容,none,none,none,none,‘密码区’,密码,none,none,none # 货物名,none,规格,单位,数量,单价,none,none,金额,税率,税额 # ‘价税合计’,none,金额,none,none,none,none,none,none,none,none # ‘销售方’,内容,none,none,none,none,‘备注’,备注,none,none,none # 购买方 purchaser = table[0][1].replace(" ", "") purchaser_name = re.search(r'名称(:|:)(. )', purchaser) invoice.purchaser_name = purchaser_name.group(2) if purchaser_name else '' purchaser_tax_number = re.search(r'纳税人识别号(:|:)(. )', purchaser) invoice.purchaser_tax_number = purchaser_tax_number.group(2) if purchaser_tax_number else '' purchaser_address = re.search(r'地址、电话(:|:)(. )', purchaser) invoice.purchaser_address = purchaser_address.group(2) if purchaser_address else '' purchaser_bank = re.search(r'开户行及账号(:|:)(. )', purchaser) invoice.purchaser_bank = purchaser_bank.group(2) if purchaser_bank else ''导出数据到excel

使用openpyxl可以很简单地将识别到的发票数据导出到excel文件。

workbook = openpyxl.Workbook() sheet=workbook[workbook.sheetnames[0]] # 导出开票日期、发票代码、发票号码、校验码、购买方名称和税号、销售方名称和税号、价格、税率、税额、价税合计、备注 sheet.append(['开票日期','发票代码','发票号码','校验码','购买方名称','购买方税号','销售方名称','销售方税号','价格','税率','税额','价税合计','备注']) for i in range(row): invoice = invoices[i] sheet.append([invoice.date,invoice.code,invoice.number,invoice.check_code,invoice.purchaser_name,invoice.purchaser_tax_number,invoice.seller_name,invoice.seller_tax_number,invoice.total_amount,invoice.tax_rate,invoice.total_tax,invoice.total,invoice.remark]) workbook.save(output_path)

导出表格示例如下图:

table表格线条怎么加上,table去掉表格的横向和竖向边框(3)

合并发票文件

由于pdfplumber不能很好的编辑PDF文件,这里我们使用PyPDF4来处理PDF的合并,代码也很简单:

from PyPDF4 import PdfFileMerger merger = PdfFileMerger() for invoice_path in invoice_paths: merger.append(invoice_path) merger.write(output_path) merger.close()

为了节省纸张,有些公司会在一张A4纸打印2张发票,这里我们不去实现两张发票合并到一个页面的功能,这个可以在文件打印的时候选择一页打印多张PDF。

table表格线条怎么加上,table去掉表格的横向和竖向边框(4)

源码

最后,干货必须带源码~

python版本为3.8,需要安装的依赖包如下requirements.txt:

pdfplumber~=0.6.1 PyPDF4~=1.27.0 openpyxl~=3.0.7

invoice.py

import pdfplumber from PyPDF4 import PdfFileMerger import openpyxl import re,time,os class Invoice: def __init__(self): # 发票类型、发票号码、开票日期、机器编号、发票代码、校验码 self.type=self.number=self.date=self.machine_number=self.code=self.check_code = '' # 收款人、复核、开票人 self.payee=self.reviewer=self.drawer = '' # 购买方名称、纳税人识别号、地址电话、开户行及账号 self.purchaser_name=self.purchaser_tax_number=self.purchaser_address=self.purchaser_bank = '' # 密码 self.password = '' # 合计金额、合计税额、税率、价税合计 self.total_amount=self.total_tax=self.tax_rate=self.total = '' # 销售方名称、纳税人识别号、地址电话、开户行及账号 self.seller_name=self.seller_tax_number=self.seller_address=self.seller_bank = '' # 备注 self.remark = '' # 解析PDF格式电子发票 @staticmethod def read_invoice(pdf_file: str) -> "Invoice": invoice = Invoice() try: with pdfplumber.open(pdf_file) as pdf: # 读取第一页 first_page = pdf.pages[0] # 读取文本 text = first_page.extract_text().replace(" ", "") # print(text) if '专用发票' in text: invoice.type = '专票' elif '普通发票' in text: invoice.type = '普票' else: raise Exception('未知发票类型或非发票文件') # 提取发票表格上方内容 invoice.number = re.search(r'发票号码(:|:)(\d )', text).group(2) invoice.date = re.search(r'开票日期(:|:)(.*)', text).group(2) invoice.machine_number = re.search(r'机器编号(:|:)(\d )', text).group(2) invoice.code = re.search(r'发票代码(:|:)(\d )', text).group(2) invoice.check_code = re.search(r'校验码(:|:)(\d )', text).group(2) # 提取发票表格下方内容,全在一行里 match = re.search(r'.*收款人(:|:)(.*)复核(:|:)(.*)开票人(:|:)(.*)销售', text) invoice.payee = match.group(2) invoice.reviewer = match.group(4) invoice.drawer = match.group(6) # 读取表格 table = first_page.extract_table() # 表格为4行11列 # ‘购买方’,内容,none,none,none,none,‘密码区’,密码,none,none,none # 货物名,none,规格,单位,数量,单价,none,none,金额,税率,税额 # ‘价税合计’,none,金额,none,none,none,none,none,none,none,none # ‘销售方’,内容,none,none,none,none,‘备注’,备注,none,none,none if table and len(table)==4: # 购买方 purchaser = table[0][1].replace(" ", "") purchaser_name = re.search(r'名称(:|:)(. )', purchaser) invoice.purchaser_name = purchaser_name.group(2) if purchaser_name else '' purchaser_tax_number = re.search(r'纳税人识别号(:|:)(. )', purchaser) invoice.purchaser_tax_number = purchaser_tax_number.group(2) if purchaser_tax_number else '' purchaser_address = re.search(r'地址、电话(:|:)(. )', purchaser) invoice.purchaser_address = purchaser_address.group(2) if purchaser_address else '' purchaser_bank = re.search(r'开户行及账号(:|:)(. )', purchaser) invoice.purchaser_bank = purchaser_bank.group(2) if purchaser_bank else '' # 密码区 invoice.password = table[0][7].replace("\n", "") # 合计金额、税额 invoice.total_amount = table[1][8].split("\n")[-1].replace("¥", "").replace(" ", "").replace(",", "") invoice.total_amount = float(invoice.total_amount) # 注意有的发票税额为0是'*',无法直接转成数值 invoice.total_tax = table[1][10].split("\n")[-1].replace("¥", "").replace(" ", "").replace("*", "0").replace(",", "") invoice.total_tax = float(invoice.total_tax) if invoice.total_tax else 0 # 税率,一般一张发票中货品税率一致;也可以用(总税额/总金额)计算税率 invoice.tax_rate = table[1][9].split("\n")[-1].replace(" ", "").replace("%", "").replace("*", "0") invoice.tax_rate = float(invoice.tax_rate)/100 if invoice.tax_rate else 0 # invoice.tax_rate = invoice.total_tax / invoice.total_amount # 价税合计,解析或计算 invoice.total = re.search(r'. ¥(. )', table[2][2]).group(1).replace(" ", "").replace(",", "") invoice.total = float(invoice.total) # invoice.total = invoice.total_tax invoice.total_amount # 销售方 seller = table[3][1].replace(" ", "") invoice.seller_name = re.search(r'名称(:|:)(. )', seller).group(2) invoice.seller_tax_number = re.search(r'纳税人识别号(:|:)(. )', seller).group(2) seller_address = re.search(r'地址、电话(:|:)(. )', seller) invoice.seller_address = seller_address.group(2) if seller_address else '' seller_bank = re.search(r'开户行及账号(:|:)(. )', seller) invoice.seller_bank = seller_bank.group(2) if seller_bank else '' # 备注 invoice.remark = table[3][7].replace("\n", "") except Exception as e: print(pdf_file, e) return invoice #导出到excel @staticmethod def export_to_excel(invoices:"list[Invoice]", output_path:str): row = len(invoices) if invoices else 0 if row == 0: print("没有可导出的数据") return try: workbook = openpyxl.Workbook() sheet=workbook[workbook.sheetnames[0]] # 导出开票日期、发票代码、发票号码、校验码、购买方名称和税号、销售方名称和税号、价格、税率、税额、价税合计、备注 sheet.append(['开票日期','发票代码','发票号码','校验码','购买方名称','购买方税号','销售方名称','销售方税号','价格','税率','税额','价税合计','备注']) for i in range(row): invoice = invoices[i] sheet.append([invoice.date,invoice.code,invoice.number,invoice.check_code,invoice.purchaser_name,invoice.purchaser_tax_number,invoice.seller_name,invoice.seller_tax_number,invoice.total_amount,invoice.tax_rate,invoice.total_tax,invoice.total,invoice.remark]) workbook.save(output_path) except Exception as e: print('导出到excel失败', e) # 合并pdf @staticmethod def merge_pdf(invoice_paths:"list[str]", output_path:str): if len(invoice_paths) == 0: print("没有可合并的pdf") return try: merger = PdfFileMerger() for invoice_path in invoice_paths: merger.append(invoice_path) merger.write(output_path) merger.close() except Exception as e: print('合并pdf失败', e) if __name__ == '__main__': # 发票所在文件夹,使用绝对路径 path = r'E:\playground\python_tools\pdf' # 输出文件路径 output_path = os.path.join(path, 'output') if not os.path.exists(output_path): os.makedirs(output_path) # 发票内容列表 invoices = [] # 发票文件路径列表 invoice_paths = [] #列出目录的下所有文件 lists = os.listdir(path) for item in lists: if item.endswith('.pdf'): item = os.path.join(path, item) invoice = Invoice.read_invoice(item) # 仅保存解析成功的pdf if invoice and invoice.type: invoices.append(invoice) invoice_paths.append(item) # 导出发票内容到excel Invoice.export_to_excel(invoices, f'{output_path}/invoice_{time.strftime("%Y%m%d_%H%M%S", time.localtime())}.xlsx') # 合并发票到一个pdf Invoice.merge_pdf(invoice_paths, f'{output_path}/merged_invoice_{time.strftime("%Y%m%d_%H%M%S", time.localtime())}.pdf')

栏目热文

table表格怎么设置(怎么在table表格添加一行)

table表格怎么设置(怎么在table表格添加一行)

数据表也称为模拟运算表,是Excel图表的一种元素,它可以在图表的下方显示数据源中的数据。本文将介绍如何使用Spire....

2022-10-29 00:52:11查看全文 >>

table表格的各种属性(table中什么属性设置表格宽度)

table表格的各种属性(table中什么属性设置表格宽度)

点击右上方红色按钮关注“小郑搞码事”,每天都能学到知识,搞懂一个问题!单纯的table应该比CSS还要老,也就是说在出现...

2022-10-29 00:46:17查看全文 >>

table表格线样式(table表格折叠)

table表格线样式(table表格折叠)

表格table上的斜线,一般用在首行首列上,这个东西大家肯定都不陌生,在excel打印文档时我们时常都能碰到,那么在ht...

2022-10-29 00:39:24查看全文 >>

table表格怎么左右插入(table表格怎样塞入图片)

table表格怎么左右插入(table表格怎样塞入图片)

安装windows 下载地址:https://dev.mysql.com/downloads/mysql/liunx安装...

2022-10-29 01:19:44查看全文 >>

table表格上下合并(table表格两行合并成一行)

table表格上下合并(table表格两行合并成一行)

成长是一辈子的事儿!大家好!我是时问新。分享前端、Python等技术,以及个人成长路上的那些事儿。表格是可以进行单元格的...

2022-10-29 01:01:04查看全文 >>

table怎么设置一行表格的大小(table表格中设置字体大小)

table怎么设置一行表格的大小(table表格中设置字体大小)

功能说明:设置excel的属性:表格的宽度和高度,以及背景色(2红色/3绿色/4蓝色/5黄色)、边框样式(细实线:1,小...

2022-10-29 01:00:05查看全文 >>

table表格样式(怎么用table做表格)

table表格样式(怎么用table做表格)

背景:在使用layui table展示列表数据的时候,有时候单元格的内容有多行,这个时候需要设置单元格的高度自适应,这种...

2022-10-29 01:00:15查看全文 >>

table怎么快速背下来(怎么把table去重)

table怎么快速背下来(怎么把table去重)

Table 在Excel的菜单版本中以列表形式开始,但在功能区版本中它们变得更加强大。将数据范围转换为表可以扩展功能,然...

2022-10-29 00:38:35查看全文 >>

table表格怎么弄(table表格怎么添加图片)

table表格怎么弄(table表格怎么添加图片)

学习目标掌握MySQL服务中表的操作方法,能够完成表的创建,查看,重命名和删除。DDL之数据表操作(TABLE)在操作数...

2022-10-29 00:55:44查看全文 >>

使用table元素定义表格(table动态添加表格)

使用table元素定义表格(table动态添加表格)

HTML 表格实例:First NameLast NamePointsJillSmith50EveJackson94Jo...

2022-10-29 01:07:01查看全文 >>

文档排行