Search code examples
pythonexcelopenpyxlcopy-paste

How to paste values only in Excel using Python and openpyxl


I have an Excel worksheet. In column J i have some some source data which i used to make calculations in column K. Column K has the values I need, but when i click on a cell the formula shows up. I only want the values from column K, not the formula. I read somewhere that i need to set data only=True, which I have done. I then pasted data from Column K to Column L(with the intention of later deleting Columns J and K). I thought that Column L will have only the values from K but if i click on a cell, the formula still shows up. How do I simply paste values only from one column to another?

import openpyxl
wb = openpyxl.load_workbook('edited4.xlsx', data_only=True)
sheet = wb['Sheet1']

last_row = 100  
for i in range(2, last_row):
    cell = "K" + str(i)
    a_cell = "J" + str(i)
    sheet[cell] = '=IF(' + a_cell + '="R","Yes","No")'

rangeselected = []
for i in range (1, 100,1):
    rangeselected.append(sheet.cell(row = i, column = 11).value)
for i in range (1, 1000,1):
   sheet.cell(row=i, column=12).value = rangeselected[i-1]

wb.save('edited4.xlsx')

Solution

  • It's been a while since I've used openpyxl. But:

    Openpyxl doesn't run an Excel formula. It reads either the formula string or the results of the last calculation run by Excel*. This means that if a calculation is created outside of Excel, and the file has never been open by Excel, then only the formula will be available. Unless you need to display (for historical purposes, etc.) what the formula is, you should do the calculation in Python - which will be faster and more efficient anyway.

    * When I say Excel, I also include any Excel-like spreadsheet that will cache the results of the last run.

    Try this (adjust column numbers as desired):

    import openpyxl
    wb = openpyxl.load_workbook('edited4.xlsx', data_only=True)
    sheet = wb['Sheet1']
    
    last_row = 100  
    data_column = 11
    test_column = 12
    result_column = 13
    
    for i in range(2, last_row):
        if sheet.cell(row=i, column=test_column).value == "R":
            sheet.cell(row=i, column=result_column).value = "Yes"
        else:
            sheet.cell(row=i, column=result_column).value = "No"
    
    wb.save('edited4.xlsx')
    

    If you have a well-formed data sheet, you could probably shorten this by another step or two by using enumerate() and Worksheet.iter_rows() but I'll leave that to your imagination.