写入多个表格
import pandas as pd
from openpyxl import load_workbook
import os
if os.path.exists(output_file):
with pd.ExcelWriter(output_file, engine='openpyxl') as excel_writer:
book = load_workbook(excel_writer.path)
excel_writer.book = book
result_df.to_excel(excel_writer, sheet_name=sheet_name)
else:
result_df.to_excel(output_file, sheet_name=sheet_name)
pd.ExcelWriter() 可选重要参数 mode: ‘w’, ‘a’ write or append default write 测试当mode:'a’时会创建新的sheet 并没有append if_sheet_exists{‘error’, ‘new’, ‘replace’}, default ‘error’ new in 1.3.0
使用上下文管理器这样就不用担心忘记excel_writer.close()
with pd.ExcelWriter(path, mode='a', engine='openpyxl') as excel_writer:
df.to_excel(excel_writer, sheet_name='1')
多次运行会新建sheet, sheet_name很奇怪,
获取excel全部表名
excel = pd.read_excel(sheet_name=None)
excel.keys()
excel = pd.ExcelFile()
excel.sheet_names
|