有A、B、C、D、E5个文档 如果xlsx的sheet2中C2不为空,则调用并合并A、B文档。 如果xlsx的sheet2中C3或C4或C5或C6不为空,则调用并合并A、B、C文档。 如果xlsx的sheet2中C7不为空,则调用并合并A、B、C、D文档。 如果xlsx的sheet2中C8不为空,则调用并合并A、B、C、E文档。 并且避免重复合并文档
时间: 2023-12-25 21:02:37 浏览: 134
你可以使用以下代码来实现:
```python
import os
from openpyxl import load_workbook
# 读取Excel文件
workbook = load_workbook(filename='yourfile.xlsx')
sheet = workbook['Sheet2']
# 判断C列是否为空
if sheet['C2'].value:
# 合并A、B文档
merge_files(['A.txt', 'B.txt'], 'AB.txt')
if sheet['C3'].value or sheet['C4'].value or sheet['C5'].value or sheet['C6'].value:
# 合并A、B、C文档
merge_files(['A.txt', 'B.txt', 'C.txt'], 'ABC.txt')
if sheet['C7'].value:
# 合并A、B、C、D文档
merge_files(['A.txt', 'B.txt', 'C.txt', 'D.txt'], 'ABCD.txt')
if sheet['C8'].value:
# 合并A、B、C、E文档
merge_files(['A.txt', 'B.txt', 'C.txt', 'E.txt'], 'ABCE.txt')
# 合并文档
def merge_files(file_list, merged_file_name):
# 如果合并后的文件已存在,则直接返回
if os.path.exists(merged_file_name):
return
# 合并文件内容
with open(merged_file_name, 'w') as merged_file:
for file_name in file_list:
with open(file_name, 'r') as f:
merged_file.write(f.read())
```
这个代码首先读取`xlsx`文件中`Sheet2`中的C列的值,根据不同的值调用不同的合并函数,合并文档。如果合并后的文件已经存在,则直接返回。
你可以根据你的具体需求修改文件名和路径。
阅读全文
相关推荐











