将pandas.DataFrame添加到现有Excel文件

时间:2017-03-03 22:55:22

标签: python excel python-3.x pandas openpyxl

我有一个网络刮刀,可以为本月创建一个excel文件。我希望每次运行时将今天的刮擦和当月的每次刮擦添加到该文件中作为新的工作表。然而,我的问题是它只用新的表覆盖现有的表,而不是将其作为单独的新表添加。我试过用xlrd,xlwt,pandas和openpyxl来做这件事。

仍然是Python的新手,所以简单得到赞赏!

下面是处理编写excel文件的代码。

# My relevant time variables
ts = time.time()
date_time = datetime.datetime.fromtimestamp(ts).strftime('%y-%m-%d %H_%M_%S')
HourMinuteSecond = datetime.datetime.fromtimestamp(ts).strftime('%H_%M_%S')
month = datetime.datetime.now().strftime('%m-%y')

# Creates a writer for this month and year
writer = pd.ExcelWriter(
    'C:\\Users\\G\\Desktop\\KickstarterLinks(%s).xlsx' % (month), 
    engine='xlsxwriter')

# Creates dataframe from my data, d
df = pd.DataFrame(d)

# Writes to the excel file
df.to_excel(writer, sheet_name='%s' % (HourMinuteSecond))
writer.save()

1 个答案:

答案 0 :(得分:4)

更新

此功能已添加到pandas 0.24.0

  

ExcelWriter现在接受df['E'].apply(lambda x: x*1000000 if isinstance(x, (int, float)) else np.nan) 作为关键字参数,在使用openpyxl引擎(GH3441)时可以附加到现有工作簿

以前的版本:

Pandas有open feature request

同时,这是一个向现有工作簿添加mode的函数:

<强>代码:

pandas.DataFrame

测试代码:

def add_frame_to_workbook(filename, tabname, dataframe, timestamp):
    """
    Save a dataframe to a workbook tab with the filename and tabname
    coded to timestamp

    :param filename: filename to create, can use strptime formatting
    :param tabname: tabname to create, can use strptime formatting
    :param dataframe: dataframe to save to workbook
    :param timestamp: timestamp associated with dataframe
    :return: None
    """
    filename = timestamp.strftime(filename)
    sheet_name = timestamp.strftime(tabname)

    # create a writer for this month and year
    writer = pd.ExcelWriter(filename, engine='openpyxl')

    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)

        # copy existing sheets
        writer.sheets = dict(
            (ws.title, ws) for ws in writer.book.worksheets)
    except IOError:
        # file does not exist yet, we will create it
        pass

    # write out the new sheet
    dataframe.to_excel(writer, sheet_name=sheet_name)

    # save the workbook
    writer.save()

Source