使用pandas将工作表添加到现有的Excel文件

# Set the working folder to the same folder as the script os.chdir(os.path.dirname(os.path.abspath(__file__))) test = send_request().content df = pd.read_csv(io.StringIO(test.decode('utf-8'))) writer = pd.ExcelWriter('NHL_STATS_JSB_final.xlsx', \ engine = 'xlsxwriter') df.to_excel(writer, 'Player statistics', index=False) writer.save() 

我不明白为什么,但我试图将工作表Player statistics添加到我当前的NHL_STATS_JSB_final.xlsx文件,但它不工作。 我的代码不是将工作表添加到文件中,而是使用当前文件并删除以前的所有工作表来添加新的工作表。

我怎样才能删除所有其他的工作表添加Player statistics到我目前的Excel文件?

这里是我的一个项目的代码片段。 这应该做你想要的。 您需要使用openpyxl而不是xlsxwriter来允许您更新现有的文件。

 writer = pd.ExcelWriter(file_name, engine='openpyxl') if os.path.exists(file_name): book = openpyxl.load_workbook(file_name) writer.book = book df.to_excel(writer, sheet_name=key) writer.save() writer.close() 

正如OP提到的,xlsxwriter将覆盖您现有的工作簿。 Xlsxwriter用于编写原始的.xlsx文件。 另一方面,Openpyxl可以修改现有的.xlsx文件。

@Brad Campbell回答使用openpyxl是做到这一点的最好方法。 由于OP使用的是xlsxwriter引擎,因此我想演示如何读取现有的.xlsx文件,然后创build一个包含原始表单和新表单的新工作簿(同名)我想补充一下。

 import pandas as pd import os xl = pd.ExcelFile('NHL_STATS_JSB_final.xlsx') sheet_names = xl.sheet_names # a list of existing sheet names #the next three lines are OPs original code os.chdir(os.path.dirname(os.path.abspath(__file__))) test = send_request().content df = pd.read_csv(io.StringIO(test.decode('utf-8'))) #beginning the process of creating new workbook with the same name writer = pd.ExcelWriter('NHL_STATS_JSB_final.xlsx', engine = 'xlsxwriter') d = {} #creating an empty dictionary for i in range (0, len(sheet_names)): current_sheet_name = sheet_names[i] d[current_sheet_name] = pd.read_excel('NHL_STATS_JSB_final.xlsx', sheetname = i) d[current_sheet_name].to_excel(writer, '%s' % (current_sheet_name), index=False) # adding in the new worksheet df.to_excel(writer, 'Player statistics', index=False) writer.save()