简体   繁体   中英

Formatting cells with the Google Sheets API (v4)

I'm using the Google Sheets API (v4) to create/update spreadsheets programmatically and have run into the following issue:

As per the documentation ( https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/cells#CellFormat ), I'm setting the number format to CURRENCY ; this will correctly display the number as a numeric value with a ¥ sign at the front (Japanese locale). However, it does not seem to actually select the "Currency" option on the formats dropdown, and more importantly, does NOT reflect the specified format when downloading the spreadsheet (eg as an.xlsx file).

在此处输入图像描述

This is different from selecting the 'Currency' option manually (via the UI), in which case values are correctly displayed once downloaded.

在此处输入图像描述

Here's the relevant section of code:


import { google, sheets_v4 } from 'googleapis';

const sheetsApi = google.sheets({
  version: 'v4',
  auth: await this.getAuthClient(),
});

await sheetsApi.spreadsheets
  .batchUpdate({
    spreadsheetId: resource,
    requestBody: {
      requests: [
        {
          updateSpreadsheetProperties: {
            fields: 'locale',
            properties: {
              locale: 'ja',
            },
          },
        },

        ...,
        
        {
          repeatCell: {
            fields: 'userEnteredFormat.numberFormat',
            cell: {
              userEnteredFormat: {
                numberFormat: { type: 'CURRENCY' },
              },
            },
          },
        },
      ],
    },
  })
  .catch((error) => {
    console.log(error);
  });

I've also tried settings the pattern (tried few different ones), but haven't been able to actually set the cell format, despite the value being displayed as such.

Probably a simple mistake, but I've been stuck on this for a while.. any help would be greatly appreciated!

In that case, I thought that the property of pattern might be required to be set. So in this case, how about modifying your request of repeatCell as follows?

Modified request:

{
  "repeatCell": {
    "range": {,,,}, // Please set range.
    "cell": {
      "userEnteredFormat": {
        "numberFormat": {
          "type": "CURRENCY",
          "pattern": "[$¥-411]#,##0.00"  // <--- Added
        }
      }
    },
    "fields": "userEnteredFormat.numberFormat"  // or "fields": "userEnteredFormat"
  }
}

Note:

  • In my environment, when above modified request is used for the batchUpdate method, I could confirm that "Currency" was checked.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM