Tengo una serie de valores que quiero insertar en una hoja de Google a través de la API, necesito dar formato de color a ciertas celdas según el contenido de la celda como la imagen a continuación:
Puedo insertar los valores usando agregar pero no he encontrado ningún ejemplo sobre cómo formatear solicitudes de agregar.
let values = [["Department", "Product", "Cost", "Status"], ["Clothes", "Socks", "12" "On Stock"], ["Clothes", "Hat", "15.99", "Out of stock"], ["Fresh","Apple", "18", "Pending"], ["Fresh", "Bannana", "17" "Out of stock"], ["Kitchen", "Spoon", "0.99", "Out of stock"]] await googleSheets.spreadsheets.values.append({ auth, spreadsheetId, range: "Products", valueInputOption: "USER_ENTERED", resource: { values: values, }, });¿Cuál es el mejor enfoque para lograr esto? actualización por lotes? ¿Cómo se implementaría con batchUpdate?
En su situación, ¿qué le parece usar ConditionalFormatRule? Cuando se usa ConditionalFormatRule, cuando se ejecuta un script una vez, los colores se reflejan automáticamente. Para lograr esto, un script de muestra es el siguiente.
const googleSheets = google.sheets({ version: "v4", auth }); // Please use your authorization script. const spreadsheetId = "###"; // Please set Spreadsheet ID. const sheetId = "###"; // Please set Sheet ID. // These values and colors are from your showing image. const colorObj = [ { value: "On Stock", rgb: [182, 215, 168] }, // #b6d7a8 { value: "Out of stock", rgb: [244, 204, 204] }, // #f4cccc { value: "Pending", rgb: [252, 229, 205] }, // #fce5cd ]; const requests = colorObj.map(({ value, rgb }, i) => ({ addConditionalFormatRule: { index: 0, rule: { booleanRule: { condition: { values: [ { userEnteredValue: value, }, ], type: "TEXT_EQ", }, format: { backgroundColor: { red: rgb[0] / 255, green: rgb[1] / 255, blue: rgb[2] / 255, }, }, }, ranges: [ { sheetId, startColumnIndex: 3, endColumnIndex: 4, startRowIndex: 1, }, ], }, }, })); const res = await googleSheets.spreadsheets.batchUpdate({ spreadsheetId, resource: { requests }, });