很多时候我们从库里面读了很多表,需要使用excel 对它进行加工释义,或增加字段,方便更多成员了解它、管理它。
Python 往excel 里面特定地方写入数据,让excle公式能有效,使用openpyxl 实现
如果以下是模板,需要往红色区域写入文字(读取几百张表结构,都要生成这样的样式和公式)
结果如下图,每个sheetname ,都是表名;字段写入特定位置
上代码:
# 根据表结构(多个)生成到excel(按表名在不同的sheet) 里面
import pandas as pd
from openpyxl import load_workbook
# 读取要写的数据
def read_df(file_name, sheet_name):
all_df = pd.read_excel(file_name, sheet_name=sheet_name)
table_series = all_df.drop_duplicates('TABLE_NAME')['TABLE_NAME']
table_list = list(table_series)
return table_list, all_df
# 读取模板生成110对应的模板.
def gen_temp(temp_file, table_list):
wb = load_workbook(temp_file, keep_vba=True)
print(len(table_list))
for i in range(0, len(table_list)):
ws = wb.worksheets[4]
index = 'a' + str(i)
index = wb.copy_worksheet(wb.worksheets[4])
index.title = table_list[i]
index.title = table_list[i]
# 读取模板生成110对应的模板.
wb.save('template_one.xlsm')
return wb
# 往模板里面写数据
def get_excel(table, index, all_df, wb):
df = all_df[all_df['TABLE_NAME'] == table]
ws = wb.get_sheet_by_name(table)
for i in range(0, len(df)):
begin_row = 13
row = begin_row + i
Column_Name = df['COLUMN_NAME'].iloc[i]
Display_Name = df['COLUMN_NAME'].iloc[i]
Description = df['COLUMN_COMMENT'].iloc[i]
Datatype = df['ORACLE_TYPE'].iloc[i]
size = df['PRECISION'].iloc[i]
isNULL = df['ISNULLABLE'].iloc[i]
key = df['ISPK'].iloc[i]
Default_Value = df['DEFAULT_VALUE'].iloc[i]
ws.cell(row=row, column=1).value = Column_Name
ws.cell(row=row, column=2).value = Display_Name
ws.cell(row=row, column=3).value = Description
ws.cell(row=row, column=4).value = Datatype
ws.cell(row=row, column=5).value = size
ws.cell(row=row, column=6).value = isNULL
ws.cell(row=row, column=8).value = Default_Value
ws.cell(row=row, column=9).value = key
ws.cell(row=3, column=2).value = df['TABLE_COMMENT'].iloc[0]
# 在一个excle 里面循环生成sheetname
def gen_final_excel(table_list, all_df, wb, gen_excel):
wb = load_workbook(r'template_one.xlsm', keep_vba=True)
for i in range(0, len(table_list)):
index = 'a' + str(i)
get_excel(table_list[i], index, all_df, wb)
# 最终文档
wb.save(gen_excel)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# 读取要生成表的数据文件,@param1 excle文件名 @param2 sheetname 返回table_list 几个表,all_df 是所有的数据
table_list, all_df = read_df('表结构.xlsx', '新预定')
# @param1要成excel 的模板,@param2 所有的表名,返回wb 是openpyxl 方式
wb = gen_temp(r'EP_EDW_DM_DSGN (ora)-(FT_DWS_CUSTOMS_TRADE).xlsm', table_list)
# 生成exlce @param1 所有表,@param2所有数据 ,@param3 生成的文件名
gen_final_excel(table_list, all_df, wb, '新预定1.xlsm')
表结构.xlsx:里面有110张表结构,