# python汇总excel数据
Date: 2020-01-31


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

- 环境：
    
    - windows10
    - python3.7 + openpyxl
- 目标：
    
    以data1数据为准，通过查找data2补全相关信息, 将数据填入要求的result文件中。
    
- 表格格式:
    
    - 表格1 `data1.xlsx`
    
    | 姓名 |
    | --- |
    | 张三 |
    | 李四 |
    
    - 表格2 `data2.xlsx`
    
    | 序号 | 姓 名 | 性别 | 身份证号 | 联系电话 |
    | --- | --- | --- | --- | --- |
    | 01 | 张三 | 男 | 130012345678901234 | 13911111111 |
    | 02 | 李四 | 男 | 123012345678901234 | 13922222222 |
    | 03 | 王五 | 男 | 123012345678901234 | 13933333333 |
    
    - 表格3 `result.xlsx`
    
    | 序号 | 所属部门 | 厂商 | 姓名 | 身份证号 | 联系电话 | 备注 |
    | --- | --- | --- | --- | --- | --- | --- |
    |  |  |  |  |  |  |  |
    
- 代码:
    

```python
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') 

```

- 运行结果

| 序号 | 所属部门 | 厂商 | 姓名 | 身份证号 | 联系电话 | 备注 |
| --- | --- | --- | --- | --- | --- | --- |
| 1 | XX部 | XXX | 张三 | 130012345678901234 | 13911111111 |  |
| 2 | XX部 | XXX | 李四 | 130012345678901234 | 13922222222 |  |

### 参考

[Openpyxl Doc](https://openpyxl.readthedocs.io/en/stable/index.html#) [Using openpyxl to find rows that contain cell with specific value (Python 3.6)](https://stackoverflow.com/questions/51800122/using-openpyxl-to-find-rows-that-contain-cell-with-specific-value-python-3-6)

