记录excel的存在判断,数据是写入还是新增
本质还是对原有数据进行读取到DataFrame,在添加新数据到DataFrame,然后将DataFrame重写回excel
# pip install xlwt
import os
import time
import datetime
import xlwt
import pandas
def append_data_to_excel(feed_info: dict, save_path="../data/vedio_20240517.xlsx"):
if not os.path.exists(save_path):
workbook = xlwt.Workbook(encoding="utf-8-sig", style_compression=0)
# 创建工作表
worksheet = workbook.add_sheet(sheetname='one', cell_overwrite_ok=True)
# 定义你要写入的列名称
col_name = list(feed_info.keys())
for col in range(len(col_name)):
worksheet.write(0, col, col_name[col])
workbook.save(save_path)
else:
print(f'{save_path} 已经存在')
original_data = pandas.read_excel(save_path)
print("开始保存到:{} ---------".format(save_path))
# 多行数据格式必须是 字典{'列名': [该列数据····],
# '列名': [该列数据····]
# }
new_data = pandas.DataFrame([feed_info])
save_data = pandas.concat([original_data, new_data], ignore_index=True)
save_data.to_excel(save_path, index=False)
print("保存成功:^_^")
if __name__ == '__main__':
today = datetime.datetime.now().strftime("%Y%m%d")
save_path = "../data/vedio_{}.xlsx".format(today)
# 测试使用的
feed_info = {'user_id': '3xe5j6crrc9iqqe',
'userName': '蓝光乐队',
'photoId': '3xahmw46ty7aft9',
'likeCount': '7.2万',
'viewCount': '1389157',
'timestamp': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(1715333129610 / 1000)),
'canAddComment': 0
}
append_data_to_excel(feed_info=feed_info, save_path=save_path)