import openpyxl# 创建-一个Workbook对象
wb = openpyxl.Workbook()# 创建多个工作表
sheet1 = wb.active
sheet1.title = "s1"sheet2 = wb.create_sheet("s2")# 在不同的工作表中写入数据
sheet1["A1"] = 'Data for Sheet1'
sheet1["A2"] = 'Data for Sheet1'sheet2["A1"] = 'Data for Sheet2'
sheet2["B1"] = 'Data for Sheet2'data_sheet1 = [["A", "B"], [1,2,3], ["x", "Y", "Z",3]]
for row in data_sheet1:sheet1.append(row)# 保存excel
wb.save('example.xlsx')
import pandas as pd# 创建数据
sheet1_data = {'Column1':[1,2,3], "Column2":["A", 2, "C"],"Column3":["A", 2, "C"]} # 每一列列数量必须一致
sheet2_data = {'Column3':["x", "Y", "Z"], "Column4":["4", "5", "6"]}data_sheet1 = [["A", "B",1], [1,2,3], ["x", "Y", "Z"]] # 每一行数量(每一行3个值) 和 列的数量(共计3列)保持一致# 创建DataFrame
df_sheet1 = pd.DataFrame(sheet1_data) # 按列写入
# df_sheet1 = pd.DataFrame(data_sheet1) # 按行写入 且会覆盖上一行按列写入内容
for row in data_sheet1: # 按行追加写入内容new_row_sheet1 = pd.DataFrame([row], columns=df_sheet1.columns)df_sheet1 = pd.concat([df_sheet1, new_row_sheet1], ignore_index=True)df_sheet2 = pd.DataFrame(sheet2_data)# 写入不同的工作表
with pd.ExcelWriter('example_pandas.xlsx') as writer:df_sheet1.to_excel(writer, sheet_name='s1', index=False)df_sheet2.to_excel(writer, sheet_name='s2', index=False)