import random
import time
from openpyxl import Workbook
def calculate_check_code(first_17):
"""计算身份证校验码"""
weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
check_map = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
total = sum(int(num) * weight[i] for i, num in enumerate(first_17))
return check_map[total % 11]
def generate_valid_id():
"""生成合法虚拟身份证号"""
region_code = f"{random.randint(110000, 659999):06d}"
birth_year = random.randint(1940, 2023)
try:
birth_date = time.strftime("%Y%m%d",
time.strptime(f"{birth_year}{random.randint(1, 366):03d}", "%Y%j"))
except:
birth_date = f"{birth_year}0228"
sequence = f"{random.randint(0, 999):03d}"
first_17 = region_code + birth_date + sequence
return first_17 + calculate_check_code(first_17)
generated_ids = set()
while len(generated_ids) < 20000:
generated_ids.add(generate_valid_id())
wb = Workbook()
ws = wb.active
ws.title = "ID Numbers"
for row_num, id_num in enumerate(generated_ids, 1):
ws.cell(row=row_num, column=1, value=id_num)
file_path = "D:/id.xlsx"
wb.save(file_path)
print(f"文件已生成:{file_path},共 {len(generated_ids)} 条数据")