写入excel
import pandas as pd
from openpyxl import load_workbook
# 表头
header = ['列1', '列2', '列3']
# 第一行数据
line = [['1', '1', '1', ]]
# 第二行数据
line2 = [['2', '2', '2', ]]
df1 = pd.DataFrame(line)
df2 = pd.DataFrame(line2)
new_df = df1.append(df2)
new_df.to_excel('./res.xlsx', sheet_name="sheet1", startcol=0, index=False, header=header)
追加excel,添加一行
# 第三行数据
line3 = ['3', '3', '3', ]
df3 = pd.DataFrame(line3, index =header).T
df = pd.read_excel('res.xlsx', sheet_name='sheet1')
book = load_workbook("res.xlsx")
all_df = pd.concat([df, df3], ignore_index=True)
with pd.ExcelWriter("res.xlsx") as writer:
writer.book = book
writer.sheets = {sheet.title: sheet for sheet in book.worksheets}
# new_df.to_excel(writer, sheet_name='sheet1', startcol=0, index=False, header=header)
all_df.to_excel(writer, sheet_name='sheet1', index=False)
添加多行
line4 = [['4', '4', '4', ], ['5', '5', '5', ]]
df4 = pd.DataFrame(line4, columns=header)
df = pd.read_excel('res.xlsx', sheet_name='sheet1')
book = load_workbook("res.xlsx")
all_df = pd.concat([df, df4], ignore_index=True)
with pd.ExcelWriter("res.xlsx") as writer:
writer.book = book
writer.sheets = {sheet.title: sheet for sheet in book.worksheets}
# new_df.to_excel(writer, sheet_name='sheet1', startcol=0, index=False, header=header)
all_df.to_excel(writer, sheet_name='sheet1', index=False)