openpyxl模块---------------------------------------------提取身份证信息及计算年龄

发布时间 2024-01-13 22:05:59作者: 往事已成昨天

 

上代码:

from openpyxl import load_workbook
from datetime import datetime
def create_time():
now_year = datetime.now().year
wb = load_workbook('C:/Users/admin/Desktop/11.xlsx')
sh = wb.active
max_column = sh.max_column
for i,cell in enumerate(sh['B']):
pno = cell.value
# print(pno)
##身份证的特点: #6位行政划分 4位年 2位月 2位日 4位个人编码
year = pno[6:10]
month = pno[10:12]
day = pno[12:14]
print(f'year:{year} month:{month} day:{day}')
age = now_year - int(year)
sh.cell(i + 1,max_column + 1).value = year
sh.cell(i + 1, max_column + 2).value = month
sh.cell(i + 1, max_column + 3).value = day
sh.cell(i + 1, max_column + 4).value = age
wb.save('C:/Users/admin/Desktop/time.xlsx')
if __name__ == "__main__":
create_time()

实现效果;

D:\softfiles\Python3.8解释器\python.exe C:/Users/admin/PycharmProjects/pythonProject/提取身份证信息.py
year:1989 month:12 day:17
year:1996 month:08 day:06
year:1998 month:05 day:27
year:1965 month:11 day:28
year:1976 month:11 day:14
year:1992 month:02 day:17
year:1956 month:10 day:13

Process finished with exit code 0

 坑:data表格中有空格导致,即有空值导致

Traceback (most recent call last):
File "C:/Users/admin/PycharmProjects/pythonProject/提取身份证信息.py", line 23, in <module>
create_time()
File "C:/Users/admin/PycharmProjects/pythonProject/提取身份证信息.py", line 12, in create_time
year = pno[6:10]
TypeError: 'NoneType' object is not subscriptable

Process finished with exit code 1

使用11.xlsx数据就可以了