# python excel文件中指定字段是否相等
Date: 2020-08-24


工作需要检查相关excel数据信息, 查询一个表格中的指定位置编号，检查相关多个个相关表格中指定位置编号是否相同。

#### 环境

- windows10
- python3.7 + openpyxl + xlrd

#### 测试数据

- 目录结构

```
C:.
│  checklist.py
│  reference.xlsx
│  
└─newdir
    ├─dir1
    │      data1.xls
    │      
    └─dir2
            data2.xls
```

- 文件内容
    
    - 参考表格 `reference.xlsx`
    
    | A |
    | --- |
    | CODE-12345 |
    
    - 表格1 `data1.xls`
    
    | A |
    | --- |
    | CODE-12345 |
    
    - 表格2 `data2.xlsx`
    
    | A |
    | --- |
    | CODE-67890 |
    

#### 代码

```python
from openpyxl import load_workbook
from openpyxl import Workbook
import os
import xlrd

## 获取待检查清单列表
def get_file(root_path,all_files=[]):
    files = os.listdir(root_path)
    for file in files:
        if not os.path.isdir(root_path + '/' + file):  
        # 检查文件名包含"功能点"， 以 "xls", "xlsx"为后缀的文件
            if (file.endswith('.xls') or file.endswith('.xlsx')) \
                and 'XXXX' in file:
                all_files.append(root_path + '/' + file)
        else:
        # 如果是目录，目录后增加'/'递归查找符合条件的文件
            get_file((root_path+'/'+file),all_files)
    return all_files

## 获取参考文件指定位置编号
def get_request_no(root_path):
    files = os.listdir(root_path)
    for file in files:
        if not os.path.isdir(root_path + '/' + file):  
            if file.endswith('.xls') or file.endswith('.xlsx') \
               and 'YYYY' in file:
                print (file)
                ## only xlsx
                wb_in = load_workbook(file)
                ws_in = wb_in.active
                ## 查找第2行，第5列的编号 
                request_no = ws_in.cell(row=2, column=5)
                print (request_no.value + '\n')
                ##break
    return request_no.value;

## 遍历参考列表文件记录与参考文件表中需求编号不同的文件名
def check_file(files, request_no):
    result=""
    for file in files:
        ## 由于openpyxl, 不支持xls，这里使用的是xlrd库 
        wb_in = xlrd.open_workbook(file)
        ws_in = wb_in.sheets()[0]
        ## 编号是从0开始计数， 第8行， 第2列中的数据
        file_request_no = ws_in.cell(rowx=7, colx=1)
        if str(file_request_no.value) != str(request_no):
            s = file_request_no.value + file +'\n'
            result += s 

    return result

def write_log(result):
    file=open("result.txt", "w")
    file.write(result)
    file.close()

path = r'.\\ZZZZ'
list=get_file(path)
path = r'.'
no=get_request_no(path)
result=check_file(list, no)
write_log(result)
```

#### 运行结果

```
> python check.py
> type result.txt
CODE-67890.\\newdir/dir2/data2.xls
```

### 参考

[Openpyxl Doc](https://openpyxl.readthedocs.io/en/stable/index.html#) [xlrd- API Reference](https://xlrd.readthedocs.io/en/latest/api.html)

