Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

Google Sheets API adding single qoute to text

Hi I am running a Google APi script to enter data into a sheet but for some text (number,dates, booleans) it's adding a ' before e.g 05/01/2021 = '05/01/2021

I am using batch update:

def turn_into_range(data, SheetId, row,cols):
    rows = [{'values': [{'userEnteredValue': {'stringValue': f}} for f in e]} for e in data]
    rng = {'sheetId': SheetId, 'startRowIndex': 0, 'startColumnIndex': 0}
    fields = 'userEnteredValue'
    body = {'requests': [{'updateCells': {'rows': rows, 'range': rng, 'fields': fields}},{
            "updateSheetProperties": {
                "properties": {
                    "gridProperties": {
                        "rowCount": row + 1,
                        "columnCount": cols
                    },
                    "sheetId": SheetId
                },
                "fields": "gridProperties"
            },
        
        }
                         ]}
    clean_dict = simplejson.loads(simplejson.dumps(body, ignore_nan=True))
    return clean_dict

def post_sheet(service_sheets, spreadsheet_id, body):
    request = service_sheets.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_id, body=body)
    response = request.execute()
    return response

any ideas?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For this issue, it is because your data is treated as string in stringValue.

You need to use other types of values for different data types,

stringValue:

  • "A String", # Represents a string value.
  • Leading single quotes are not included. For example, if the user typed '123 into the UI, this would be represented as a stringValue of "123".

boolValue:

  • True or False, # Represents a boolean value.

numberValue:

  • 3.14, # Represents a double value.
  • Note: Dates, Times and DateTimes are represented as doubles in "serial number" format.

formulaValue:

  • "A String", # Represents a formula.

errorValue:

  • An error in a cell. Represents an error.
  • This field is read-only.

Try adding this in your code.

from dateutil.parser import parse

def checkData(data):
    if (isinstance(data, bool)):
        return 'boolValue'
    try:
        if (isinstance(data, (int, float)) or parse(data)):
            return 'numberValue'
    except ValueError:
        return 'stringValue'

Behaviour:

sample output

Now, use it in your code:

rows = [{'values': [{'userEnteredValue': {checkData(f): f}} for f in e]} for e in data]

For more details, documentation can be found here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...