工作需要汇总整理相关excel数据信息,并按照规定格式进行反馈,用python写了一个脚本处理了一下。 样例中表格内容也进行了调整。

  • 环境:

    • windows10
    • python3.7 + openpyxl
  • 目标:

    以data1数据为准,通过查找data2补全相关信息, 将数据填入要求的result文件中。

  • 表格格式:

    • 表格1 data1.xlsx
    姓名
    张三
    李四
    • 表格2 data2.xlsx
    序号姓 名性别身份证号联系电话
    01张三13001234567890123413911111111
    02李四12301234567890123413922222222
    03王五12301234567890123413933333333
    • 表格3 result.xlsx
    序号所属部门厂商姓名身份证号联系电话备注
  • 代码:

from openpyxl import load_workbook
from openpyxl import Workbook
import pandas as pd

wb_in = load_workbook( filename = '.\\test\\data1.xlsx')
ws_in = wb_in.active
## 名字列表开始结束行号 
start_index = 2
end_index = 4

wb_info = load_workbook( filename = '.\\test\\data2.xlsx')
ws_info = wb_info.active

wb_out = load_workbook( filename = '.\\test\\result.xlsx') 
ws_out = wb_out.active
out_index = 2 

## 找到要统计人员姓名
for x in range(start_index,end_index):
    name = ws_in.cell(row=x,column=1)
    print(name.value)
    ## 查找要统计人员附件信息并更新到统计表格中
    find_flag = 0
    for row in ws_info.iter_rows("B"):
        for col in row:
            #print(col.value)
            if (str(col.value).strip() == str(name.value).strip()) and (find_flag == 0):
                ## 第四列 身份证 第五列 联系电话
                idno = ws_info.cell(row=col.row,column=4)
                phoneno = ws_info.cell(row=col.row, column=5)
                ## 更新到统计文件
                ws_out['A'+ str(out_index)].value = str(out_index-1)
                ws_out['B'+ str(out_index)].value = 'XX部'
                ws_out['C'+ str(out_index)].value = 'XXX'
                ws_out['D'+ str(out_index)].value = name.value
                ws_out['E'+ str(out_index)].value = idno.value
                ws_out['F'+ str(out_index)].value = phoneno.value
                out_index = out_index + 1
                find_flag = 1
            break
    if find_flag == 0:
        print(name.value)

wb_out.save( filename = '.\\test\\result.xlsx') 
  • 运行结果
序号所属部门厂商姓名身份证号联系电话备注
1XX部XXX张三13001234567890123413911111111
2XX部XXX李四13001234567890123413922222222

参考

Openpyxl Doc Using openpyxl to find rows that contain cell with specific value (Python 3.6)