import pandas as pd
import openpyxl
'''
實現(xiàn)追加或者覆蓋數(shù)據(jù)
data:DataFramek類型數(shù)據(jù)
excelname:工作簿名(注意路徑?。。。?/p>
sheetname:表名
insert_type:w 或者 a+ (當(dāng)然可以自己定義啦)
'''
def append_excel(data,excelname,sheetname,insert_type):
original_file = pd.DataFrame(pd.read_excel(excelname, sheet_name=sheetname)) # 讀取原數(shù)據(jù)文件和表
original_row = original_file.shape[0] # 獲取原數(shù)據(jù)的行數(shù)
if insert_type=='w': #選擇寫入excel數(shù)據(jù)方式,w為覆蓋模式,a+為追加模式
startrow=1
elif insert_type=='a+':
startrow=original_row + 1
book = openpyxl.load_workbook(excelname)
writer = pd.ExcelWriter(excelname, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
# 將data數(shù)據(jù)寫入Excel中
data.to_excel(writer, sheet_name=sheetname, startrow=startrow, index=False, header=False)
writer.save()
if __name__ == '__main__':
append_excel() #記得傳入?yún)?shù)哦
聯(lián)系客服