Search code examples
pythongoogle-sheetssteamgspreadsteamworks-api

Trying to update Google Sheet data with Python (mathematical expression), but apostrophe keep coming out


I'm new for programming, also has short Eng skill, but I will try my effort as possible.

So I made some python code. It's goal is simple. Crawling Market data (steam market), adjust those with double list data, then update it to Sheet. Plus, update mathematical expression:(Market price)*(Quantity)

I have made github, link

The thing is, inputting mathematical expression to sheet not works well. My python code keep adding apostrophe. So mathematical expression just went to mere 'String'.

I thought problem was 'update.append', so made independent function for Math like this.

def update_formulas(sheet, data):
    print("Updating formulas...")  # 
    for idx in range(2, len(data) + 2):  # 
        formula = f"=B{idx}*C{idx}"  # 
        print(f"Updating formula in D{idx}: {formula}")  # 
        sheet.update(range_name=f"D{idx}", values=[[formula]])  # 
    print("Formulas updated successfully.")  # 

But apostrophe problem keep showing. result Sheet link (D2:D5)

I made whole code with ChatGPT. I studied used libraries, commands. That's why I could make up some kind of solution(as I thought).

Maybe problem was trying to type referencing cells directly? like

=B{idx}*C{idx}

But I have no idea how to alter that.

What I tried:

Changing commands. update.append was originally "update.sheet" command. And separating function, to not Math to be recognized as "String". But whole attempts has failed.

I know I could type Math to Sheet directly, using references, but wanna solve with python code level.

Lastly, I want to use references! I know I can make Math expressions code level, like

formula = f"=price*quantity"

Ignoring grammar thing, I could use price and quantity from data previously typed, but as I said I want to use references if I could.


Solution

  • Rather than using the .update method, try using .update_cell in order to prevent interpretation of the formula as a string:

    def update_formulas(sheet, data):
        for idx in range(2, len(data) + 2):  
            formula = f"=B{idx}*C{idx}"  
            sheet.update_cell(idx, 4, formula)