Copy pandas dataframe to excel using openpyxl

前端 未结 2 975
孤独总比滥情好
孤独总比滥情好 2020-12-03 01:46

I have some complicated formating saved in a template file into which I need to save data from a pandas dataframe. Problem is when I use pd.to_excel to save to this workshee

相关标签:
2条回答
  • 2020-12-03 02:23

    openpyxl 2.4 comes with a utility for converting Pandas Dataframes into something that openpyxl can work with directly. Code would look a bit like this:

    from openpyxl.utils.dataframe import dataframe_to_rows
    rows = dataframe_to_rows(df)
    
    for r_idx, row in enumerate(rows, 1):
        for c_idx, value in enumerate(row, 1):
             ws.cell(row=r_idx, column=c_idx, value=value)
    

    You can adjust the start of the enumeration to place the cells where you need them.

    See openpyxl documentation for more information.

    0 讨论(0)
  • 2020-12-03 02:33

    Here is the solution for you using clipboard:

    import openpyxl
    import pandas as pd
    import clipboard as clp
    
    #Copy dataframe to clipboard
    df.to_clipboard()
    #paste the clipboard to a valirable
    cells = clp.paste()
    #split text in varialble as rows and columns
    cells = [x.split() for x in cells.split('\n')]
    
    #Open the work book
    wb= openpyxl.load_workbook('H:/template.xlsx')
    #Get the Sheet
    sheet = wb.get_sheet_by_name('spam')
    sheet.title = 'df data'
    #Paste clipboard values to the sheet
    for i, r in zip(range(1,len(cells)), cells):
        for j, c in zip(range(1,len(r)), r):
            sheet.cell(row = i, column = j).value = c
    #Save the workbook
    wb.save('H:/df_out.xlsx')
    
    0 讨论(0)
提交回复
热议问题