python操作excel向同一sheet循环追加数据

摘要:
参考文章:https://blog.csdn.net/sdaujz/article/details/102080900?utm_medium=distribute.pc_relevant.none-task-blog-blog从机器开始学习Pi2-15.nonecase和depth_1-utm_source=distribute.pc _ relevant.none-

参考文章:https://blog.csdn.net/sdaujz/article/details/102080900?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-15.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-15.nonecase

# 自己自定义一个方法
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False,
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.
    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]
    Returns: None
    """
    # from openpyxl import load_workbook

    # import pandas as pd

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError

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

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title: ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

测试数据:

data_list = [{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"mMdAA3MBOhUk37j9EiH2","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led strip light","pv":744.0,"pvCrc":"96.49%","clickRate":"1.01%","resultCnt":168.0,"average_pv":264,"terminalType":"PC"},"sort":["744.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"mcdAA3MBOhUk37j9EyE5","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"emerg light","pv":730.0,"pvCrc":"169.65%","clickRate":"0.30%","resultCnt":133.0,"average_pv":174,"terminalType":"PC"},"sort":["730.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"msdAA3MBOhUk37j9EyFm","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"garden light","pv":664.0,"pvCrc":"238.37%","clickRate":"0.48%","resultCnt":158.0,"average_pv":189,"terminalType":"PC"},"sort":["664.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"m8dAA3MBOhUk37j9EyHd","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"flood light","pv":631.0,"pvCrc":"369.71%","clickRate":"0.34%","resultCnt":132.0,"average_pv":140,"terminalType":"PC"},"sort":["631.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"nMdAA3MBOhUk37j9FCEI","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"solar led street light","pv":576.0,"pvCrc":"5.89%","clickRate":"0.14%","resultCnt":138.0,"average_pv":497,"terminalType":"PC"},"sort":["576.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"ncdAA3MBOhUk37j9FCEz","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led ceil light","pv":574.0,"pvCrc":"42.03%","clickRate":"0.21%","resultCnt":165.0,"average_pv":207,"terminalType":"PC"},"sort":["574.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"nsdAA3MBOhUk37j9FCGW","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"bicycl light","pv":527.0,"pvCrc":"48.92%","clickRate":"0.42%","resultCnt":88.0,"average_pv":139,"terminalType":"PC"},"sort":["527.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"n8dAA3MBOhUk37j9FCHE","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led solar light","pv":492.0,"pvCrc":"41.03%","clickRate":"0.18%","resultCnt":131.0,"average_pv":383,"terminalType":"PC"},"sort":["492.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"oMdAA3MBOhUk37j9FCH1","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led panel light","pv":490.0,"pvCrc":"-1.69%","clickRate":"4.02%","resultCnt":173.0,"average_pv":459,"terminalType":"PC"},"sort":["490.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"ocdAA3MBOhUk37j9FSE_","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led torch light","pv":382.0,"pvCrc":"-7.11%","clickRate":"0.15%","resultCnt":72.0,"average_pv":298,"terminalType":"PC"},"sort":["382.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"osdAA3MBOhUk37j9FSFq","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led grow light","pv":354.0,"pvCrc":"3.15%","clickRate":"2.98%","resultCnt":129.0,"average_pv":362,"terminalType":"PC"},"sort":["354.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"o8dAA3MBOhUk37j9FSGa","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led solar street light","pv":346.0,"pvCrc":"204.06%","clickRate":"0.13%","resultCnt":114.0,"average_pv":111,"terminalType":"PC"},"sort":["346.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"pMdAA3MBOhUk37j9FSHM","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"solar garden light","pv":341.0,"pvCrc":"-63.49%","clickRate":"0.67%","resultCnt":155.0,"average_pv":546,"terminalType":"PC"},"sort":["341.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"psdAA3MBOhUk37j9FiEk","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"auto light system","pv":310.0,"pvCrc":"303.46%","clickRate":"0.18%","resultCnt":67.0,"average_pv":75,"terminalType":"PC"},"sort":["310.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"pcdAA3MBOhUk37j9FSH3","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led solar wall light","pv":310.0,"pvCrc":"-61.57%","clickRate":"0.12%","resultCnt":73.0,"average_pv":473,"terminalType":"PC"},"sort":["310.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"p8dAA3MBOhUk37j9FiFP","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"ring light","pv":298.0,"pvCrc":"-13.34%","clickRate":"11.28%","resultCnt":105.0,"average_pv":304,"terminalType":"PC"},"sort":["298.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"qMdAA3MBOhUk37j9FiF5","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led light","pv":297.0,"pvCrc":"-10.10%","clickRate":"2.74%","resultCnt":461.0,"average_pv":344,"terminalType":"PC"},"sort":["297.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"qcdAA3MBOhUk37j9FiG9","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"solar light","pv":292.0,"pvCrc":"-19.23%","clickRate":"5.32%","resultCnt":177.0,"average_pv":285,"terminalType":"PC"},"sort":["292.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"qsdAA3MBOhUk37j9FiH2","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led fogdriv light","pv":287.0,"pvCrc":"173.15%","clickRate":"0.03%","resultCnt":11.0,"average_pv":36,"terminalType":"PC"},"sort":["287.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"NMc_A3MBOhUk37j9-iHw","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"ceil fan light","pv":19.0,"pvCrc":"33.33%","clickRate":"1.67%","resultCnt":32.0,"average_pv":13,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"Occ_A3MBOhUk37j9_SEa","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"panel led light","pv":19.0,"pvCrc":"-35.87%","clickRate":"0.00%","resultCnt":67.0,"average_pv":22,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"Psc_A3MBOhUk37j9_iHM","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led light power suppli","pv":19.0,"pvCrc":"136.00%","clickRate":"0.00%","resultCnt":41.0,"average_pv":9,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"P8c_A3MBOhUk37j9_iH4","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"quantum board led grow light","pv":19.0,"pvCrc":"9.26%","clickRate":"0.00%","resultCnt":35.0,"average_pv":25,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"QMc_A3MBOhUk37j9_yEr","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"optic light sourc and power meter","pv":19.0,"pvCrc":"-13.24%","clickRate":"0.00%","resultCnt":4.0,"average_pv":6,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"Qcc_A3MBOhUk37j9_yFY","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"light crystal","pv":19.0,"pvCrc":"728.57%","clickRate":"0.00%","resultCnt":12.0,"average_pv":7,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"Qsc_A3MBOhUk37j9_yGf","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"vaniti light","pv":19.0,"pvCrc":"-14.71%","clickRate":"0.00%","resultCnt":26.0,"average_pv":24,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"ScdAA3MBOhUk37j9ASE5","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"solar led garden light","pv":19.0,"pvCrc":"31.82%","clickRate":"6.90%","resultCnt":104.0,"average_pv":16,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"S8dAA3MBOhUk37j9ASGV","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led wall washer light","pv":19.0,"pvCrc":"7.41%","clickRate":"13.79%","resultCnt":76.0,"average_pv":20,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"PMc_A3MBOhUk37j9_iFS","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"led light rope","pv":19.0,"pvCrc":"47.50%","clickRate":"1.69%","resultCnt":28.0,"average_pv":12,"terminalType":"PC"},"sort":["19.0"]},{"_index":"numerical_keyword","_type":"numerical_keyword","_id":"Pcc_A3MBOhUk37j9_iF_","_score":'',"_source":{"search_keyword":"light","username":"cnbaronlighting","date":"2020-06-24","keyword":"fiber optic curtain light","pv":19.0,"pvCrc":"103.45%","clickRate":"0.00%","resultCnt":14.0,"average_pv":6,"terminalType":"PC"},"sort":["19.0"]}]

for num, item in enumerate(data_list):
    print(item['_source'])
    if num == 0:  # 第一次进来插入表头,自己领悟为啥这样写
        item1 = {'search_keyword': 'search_keyword', 'username': 'username', 'date': 'date', 'keyword': 'keyword',
                'pv': 'pv',
                'pvCrc': 'pvCrc', 'clickRate': 'clickRate', 'resultCnt': 'resultCnt', 'average_pv': 'average_pv',
                'terminalType': 'terminalType'}
        dfscores = pd.DataFrame(item1, index=[num])
        append_df_to_excel('1.xlsx', dfscores, sheet_name='Sheet3', header=None)
    # 开始插入数据
   dfscores
= pd.DataFrame(item['_source'], index=[num]) append_df_to_excel('1.xlsx', dfscores, sheet_name='Sheet3', startcol=0, startrow=num + 1, header=None)

结果图

 python操作excel向同一sheet循环追加数据第1张





免责声明:文章转载自《python操作excel向同一sheet循环追加数据》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇delphi NativeXml的中文支持 乱码Spring MVC原理图下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

iOS 关于时间天数星期月份的总结

#import <Foundation/Foundation.h> @interface NSDate (SLExtend) // 判断是否是本周更早 - (BOOL)isThisWeekEarlier; // 判断是否是本周晚些 - (BOOL)isThisWeekLater; // 判断是否是下一周或者更远 - (BOOL)isNextWe...

flask_apscheduler 定时任务框架

 flask 框架下定时任务通常使用 flask_apscheduler 第三方库。flask_apscheduler 功能非常强大,能满足各种定时任务的需求。   安装 pip3 install flask_apscheduler 使用方法 1.下面这段 example 是官网上的,我加了些注释,方便学习。 from flask import Flask...

php获取本周周一、周日时间,上周周一、周日时间,本月第一天,本月最后一天,上个月第一天,最后一天时间

//这个星期的星期一 // @$timestamp ,某个星期的某一个时间戳,默认为当前时间 // @is_return_timestamp ,是否返回时间戳,否则返回时间格式 function this_monday($timestamp=0,$is_return_timestamp=true){ static $cach...

python 调用接口

这个比较乱,抽口再修改一下。 工作需要调有赞API的接口数据, 返回数据. 进行数据处理 现在两部分比较重要:1 自动获取数据 , 2处理excel的过程. 明白接口的过程.传入参数 https://open.youzan.com/v3/apicenter/doc-api-main/1/2/salesman/youzan.salesman.trades.g...

python的导包问题

有事会遇到在python代码中导入包错误问题,本文简单对python包的引入做简单介绍 简单说,我认为python导包一共有3种情况,分别是: 要导的包与当前文件在同一层要导的包在当前文件的底层(就是与当前文件夹同级的文件夹里)要导的包在当前文件的上层 1、要导的包与当前文件在同一层 use.py source.py use.py表示包的调用方,sou...

关于反编译pyc的一点技巧

现在最流行的是用https://github.com/rocky/python-uncompyle6 但是有些python小版本不一样,比如2.7.6的某版本,开头的magic number在这个项目中没有收集 这时直接改开头的两字节magic number就可以反编译了 python2.7.16的是 03F3...