python 功能函数
追加存入Excel
python
from openpyxl import Workbook, load_workbook
def initialize_excel(excel_filename=EXCEL_FILENAME, sheet_name=SHEET_NAME):
"""初始化 Excel 文件,如果不存在则创建"""
if not os.path.exists(excel_filename):
wb = Workbook()
ws = wb.active
ws.title = sheet_name
# 添加标题行
headers = [
'title', 'h1', 'h2',
'author', 'description', 'url'
]
ws.append(headers)
wb.save(excel_filename)
def append_to_excel(data,excel_filename=EXCEL_FILENAME, sheet_name=SHEET_NAME):
"""将数据追加到 Excel 文件中"""
try:
wb = load_workbook(excel_filename)
ws = wb[sheet_name]
# 生成新行数据
new_row = [
data.get('title', ''),
data.get('h1', ''),
data.get('h2', ''),
data.get('author', ''),
data.get('description', ''),
data.get('url', '')
]
ws.append(new_row)
wb.save(excel_filename)
return True
except Exception as e:
print(f"Error saving to Excel: {e}")
return False