最近整理几个学期的年级排名,需要把 PDF 成绩单转成 Excel,于是研究了一下 Python 的 pdfplumber 库。整个过程并不复杂,核心就两步:用 pdfplumber 解析表格,再用 openpyxl 写入 Excel。
需要注意的是,pdfplumber 只能解析规整的表格,那种乱七八糟的格式就不太行了。好在成绩单除了标题外还算规整。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import pdfplumber from openpyxl import Workbook import os wb = Workbook() ws = wb.active path=os.getcwd()+"/2.pdf" pdf = pdfplumber.open(path) print('\n') print('开始读取数据') print('\n')
for page in pdf.pages: for table in page.extract_tables(): for row in table: rowlist=str(row).replace("[","",).replace("]","").replace("'","").replace("\\n","").split(",") ws.append(rowlist) print('---------- 分割线 ----------') pdf.close()
endfile='22.xlsx' wb.save(endfile) print('\n') print('写入excel成功') print('保存位置:') print(os.getcwd()+"/"+endfile) print('\n')
|
XMJ
Writing, Coding, Researching, and Thinking