# 读Excel数据,创建Word文档上下文字典列表,元素为每个培训人员的上下文字典
def read_sheet(_path_excel):
"""
:param _path_excel:Excel全路径
功能:读Excel数据,创建Word文档上下文字典列表,元素为每个培训人员的上下文字典
字典的键为Excel之sheet表头信息
"""
if not _path_excel.exists():
print(f'{Fore.RED}文件不存在噢!!!\n{_path_excel}{Style.RESET_ALL}')
try:
_cols = 16 # 10个单元格、3个复选框、3张图片
workbook = exApp.books.open(_path_excel) # 打开.xlsx文件
sheet = workbook.sheets[0] # 第一个数据表
sheet_list = sheet.used_range.value # 嵌套列表,sheet数据对应一个列表,每行对应一个列表,索引为0的列表为表头
workbook.close() # 关闭Excel
sheet_list = [li for li in sheet_list if li[1] is not None] # 使用列表推导式过滤掉None值行
_context_list = [] # 上下文列表,包含全部培训人员的上下文字典
for i in range(1, len(sheet_list)): # 遍历列表,第0行是表头
_context_dict = {} # 上下文字典,每个培训人员对应一个字典
for j in range(1, _cols): # 遍历列
_context_dict[sheet_list[0][j]] = str(sheet_list[i][j])
_context_list.append(_context_dict) # 将上下文字典添加到上下文列表中
# pprint(_context_list)
return _context_list
except ValueError:
fun_name = inspect.currentframe().f_code.co_name # 提取函数名称
print(f'{Fore.RED}函数"{fun_name}"异常退出!!!{Style.RESET_ALL}')
return []
# 读Excel数据,创建Word文档上下文字典列表,元素为每个培训人员的上下文字典
def create_docx_context_dict_list(_excel_path):
"""
输入参数:
:param _excel_path:Excel全路径
功能:创建Word文档上下文字典列表,元素为每个培训人员的上下文字典
字典的键为Excel之sheet表头信息
"""
warnings.simplefilter(action='ignore', category=UserWarning) # 忽略DataValidationError的警告
if not _excel_path.exists():
print(f'{Fore.RED}文件不存在噢!!!\n{_excel_path}{Style.RESET_ALL}')
try:
_cols = 16 # 10个单元格、3个复选框、3张图片
str_dict = {i: str for i in range(_cols)}
df = pd.read_excel(_excel_path, sheet_name=0, header=None, skiprows=1, converters=str_dict)
pd.set_option('future.no_silent_downcasting', True) # 不提示函数在未来版本中将被替代的警告
df = df.replace(r'\s+', '', regex=True) # 删除所有字符串列的空格
df = df.iloc[:, 1:_cols] # 取15列:B:P,跳过序号列
df = df.dropna(subset=[1]) # 删除第1列(姓名)中具有空值的行
df_list = df.values.tolist()[1:] # 数据帧转列表,每行对应一个列表(包括表头)
_head_list = df.values.tolist()[0] # 获取跳过序号的表头信息
assert len(_head_list) == len(df_list[0]) # 断言表头列数等于值列数
_context_list = [] # 上下文列表,包含全部培训人员的上下文字典
for row in range(len(df_list)): # 每行一个培训人员信息
_context_dict = {} # 上下文字典,每个培训人员对应一个字典
for i, col_value in enumerate(df_list[row]): # 按列遍历
col_label = _head_list[i] # 取每列表头信息
_context_dict[col_label] = col_value # 将字典键(列表头)值(培训人员列信息)关联
_context_list.append(_context_dict) # 将每个培训人员字典加入列表
# pprint(_context_list)
return _context_list # 返回全部培训人员列表
except ValueError:
fun_name = inspect.currentframe().f_code.co_name # 提取函数名称
print(f'{Fore.RED}函数"{fun_name}"异常退出!!!{Style.RESET_ALL}')
return []