python向excel写内容时,格式如保复用的问题
如下图,新写入的数据,要与第一列保持一致
# 定义一个函数,把df写入excel的指定位置 # start_line:excel写入的起始行 # data_df:要写入的数组 def write_excel(filepath,start_line, data_df): # 打开待写入文件 filePath =filepath tableAll = op.load_workbook(filePath) table1 = tableAll['Sheet1'] for c in range(data_df.shape[1]): for r in range(data_df.shape[0]): table1.cell(row=start_line, column=c + 2).value = data_df.columns[c] data = data_df.iloc[r, c] table1.cell(row=start_line + r + 2, column=c + 2).value = data # 以第一列复制格式 table1.cell(row=start_line + r + 2, column=c + 2).font = copy(table1.cell(row=start_line + r + 2, column=1).font) table1.cell(row=start_line + r + 2, column=c + 2).fill = copy(table1.cell(row=start_line + r + 2, column=1).fill) table1.cell(row=start_line + r + 2, column=c + 2).border = copy(table1.cell(row=start_line + r + 2, column=1).border) table1.cell(row=start_line + r + 2, column=c + 2).number_format = copy(table1.cell(row=start_line + r + 2, column=1).number_format) table1.cell(row=start_line + r + 2, column=c + 2).protection = copy(table1.cell(row=start_line + r + 2, column=1).protection) table1.cell(row=start_line + r + 2, column=c + 2).alignment = copy(table1.cell(row=start_line + r + 2, column=1).alignment) tableAll.save(filePath)
效果是这样的