pandas根据dataframe生成一个excel文件:
Dataframe保存新文件
直接把dataframe格式的数据保存到多个sheet页程序如下:
excel_file = "导出excel文件.xlsx"
if os.path.exists(excel_file):os.remove(excel_file)# 生成一个新文件
with pd.ExcelWriter(excel_file) as writer:pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="sheet1")pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="sheet2")pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="sheet3")
追加写入:
首先需要指定使用openpyxl
,然后使用pd.ExcelWriter(excel_file, engine='openpyxl', mode='a')
打开文件,在文件中直接追加即可:
with pd.ExcelWriter(excel_file, engine='openpyxl', mode='a') as writer:pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="追加sheet1")pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="追加sheet2")
完整示例
import pandas as pd
import numpy as np
import osdef main():excel_file = "导出excel文件.xlsx"if os.path.exists(excel_file):os.remove(excel_file)# 生成一个新文件with pd.ExcelWriter(excel_file) as writer:pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="sheet1")pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="sheet2")pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="sheet3")# 在已有的文件中添加with pd.ExcelWriter(excel_file, engine='openpyxl', mode='a') as writer:pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="追加sheet1")pd.DataFrame(np.random.random(size=(5, 5))).to_excel(writer, sheet_name="追加sheet2")if __name__ == '__main__':main()