2016-06-28 1839 views
6

我目前拥有这段代码。它完美的作品。使用python pandas将新的数据框添加到现有的excel表中

它通过循环Excel文件的文件夹中, 消除了前两排, 然后保存出来为单独的Excel文件, 并且还节省了在循环作为一个附加文件的文件。

当前附加文件每次运行代码时都会覆盖现有文件

我需要新的数据追加到的底部已经存在的Excel工作表('master_data.xlsx)

dfList = [] 
path = 'C:\\Test\\TestRawFile' 
newpath = 'C:\\Path\\To\\New\\Folder' 

for fn in os.listdir(path): 
    # Absolute file path 
    file = os.path.join(path, fn) 
    if os.path.isfile(file): 
    # Import the excel file and call it xlsx_file 
    xlsx_file = pd.ExcelFile(file) 
    # View the excel files sheet names 
    xlsx_file.sheet_names 
    # Load the xlsx files Data sheet as a dataframe 
    df = xlsx_file.parse('Sheet1',header= None) 
    df_NoHeader = df[2:] 
    data = df_NoHeader 
    # Save individual dataframe 
    data.to_excel(os.path.join(newpath, fn)) 

    dfList.append(data) 

appended_data = pd.concat(dfList) 
appended_data.to_excel(os.path.join(newpath, 'master_data.xlsx')) 

我以为这是一个简单的任务,但我想不会。 我想我需要将master_data.xlsx文件作为数据框引入,然后将索引与新添加的数据进行匹配,然后将其保存。或者也许有一个更简单的方法。任何帮助表示赞赏。

+0

是[that](http://stackoverflow.com/a/36450435/5741205)你在做什么? – MaxU

+0

不,不是,我不是试图保存新的工作表,只是想追加现有的工作表。 – brandog

回答

8

可以使用结合openpyxl发动机startrow参数:

In [48]: writer = pd.ExcelWriter('c:/temp/test.xlsx', engine='openpyxl') 

In [49]: df.to_excel(writer, index=False) 

In [50]: df.to_excel(writer, startrow=len(df)+2, index=False) 

In [51]: writer.save() 

C:/temp/test.xlsx:

enter image description here

PS你可能也想,如果你指定header=None不想重复列名...

UPDAT E:你可能也想检查this solution

+0

嘿谢谢,我要用这个。 (我实际上并不是仅删除2行数据,这只是大量格式化的占位符。)我需要它将追加到现有工作表的底部,而不需要索引行。 – brandog

+0

@brandog,那么你需要使用'header = None',你必须计算出excel文件中的当前行数,并像这样使用它:'startrow = curr_count + 1' – MaxU

+0

OH,哎呀!我想念。是的,这完全回答了我的问题!谢谢 – brandog

相关问题