# 读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列(姓名)具有"NaN"的行
df_head_list = df.values.tolist()[0] # 表头列表
df_info_list = df.values.tolist()[1:] # 信息列表,数据帧转列表,每行对应一个列表(包括表头)
context_dict_list = [dict(zip(df_head_list, info)) for info in df_info_list] # 将每位培训人员字典加入列表
# pprint(context_dict_list)
return context_dict_list # 返回全部培训人员列表
except ValueError:
fun_name = inspect.currentframe().f_code.co_name # 提取函数名称
print(f'{Fore.RED}函数"{fun_name}"异常退出!!!{Style.RESET_ALL}')
return []
# 读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值行
head_list = sheet_list[0][1:_cols] # 表头列表
info_list = sheet_list[1:] # 信息列表
context_dict_list = [dict(zip(head_list, info[1:_cols])) for info in info_list] # 将每位培训人员字典加入列表
# pprint(context_dict_list)
return context_dict_list
except ValueError:
fun_name = inspect.currentframe().f_code.co_name # 提取函数名称
print(f'{Fore.RED}函数"{fun_name}"异常退出!!!{Style.RESET_ALL}')
return []