0

Format Cells

by
Published today

Set bold, italic, colors, alignment, wrapping and number format on a range of cells.

Script gsheets Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 1 hour ago
1
//native
2

3
export type DynSelect_sheet_name = string
4

5
// Dropdown of the spreadsheet's worksheet (tab) names.
6
export async function sheet_name(auth: RT.Gsheets, spreadsheet_id: string) {
7
  const response = await fetch(
8
    `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}?fields=sheets.properties.title`,
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    }
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { sheets } = (await response.json()) as {
20
    sheets: { properties: { title: string } }[]
21
  }
22
  return sheets.map((s) => ({
23
    value: s.properties.title,
24
    label: s.properties.title,
25
  }))
26
}
27

28
// A1 range without the tab name (A1:F1, B:B, 2:2, C3) → GridRange; omitted bounds stay open.
29
function gridRange(sheetId: number, range: string) {
30
  const m = range.toUpperCase().match(/^([A-Z]*)(\d*)(?::([A-Z]*)(\d*))?$/)
31
  if (!m || range === "") throw new Error(`Invalid A1 range "${range}"`)
32
  const [, c1, r1, c2 = c1, r2 = r1] = m
33
  const col = (c: string) =>
34
    [...c].reduce((n, ch) => n * 26 + ch.charCodeAt(0) - 64, 0)
35
  const grid: { [key: string]: number } = { sheetId }
36
  if (c1) grid.startColumnIndex = col(c1) - 1
37
  if (c2) grid.endColumnIndex = col(c2)
38
  if (r1) grid.startRowIndex = Number(r1) - 1
39
  if (r2) grid.endRowIndex = Number(r2)
40
  return grid
41
}
42

43
// "#1a73e8" / "#fff" → Sheets Color (0-1 floats)
44
function color(hex: string) {
45
  let h = hex.replace(/^#/, "")
46
  if (h.length === 3) h = [...h].map((c) => c + c).join("")
47
  if (!/^[0-9a-f]{6}$/i.test(h)) throw new Error(`Invalid hex color "${hex}"`)
48
  const [red, green, blue] = [0, 2, 4].map(
49
    (i) => parseInt(h.slice(i, i + 2), 16) / 255
50
  )
51
  return { red, green, blue }
52
}
53

54
/**
55
 * Format Cells
56
 * Style a range (A1 notation without the tab name: `A1:F1`, `B:B`, `2:2`, `C3`). Only the attributes you set change; the rest of the formatting is kept. Colors are hex (`#1a73e8`). Number format patterns follow the Sheets syntax, e.g. `#,##0.00`, `0%`, `yyyy-mm-dd`.
57
 */
58
export async function main(
59
  auth: RT.Gsheets,
60
  spreadsheet_id: string,
61
  sheet_name: DynSelect_sheet_name,
62
  range: string,
63
  bold: boolean | undefined,
64
  italic: boolean | undefined,
65
  underline: boolean | undefined,
66
  strikethrough: boolean | undefined,
67
  font_size: number | undefined,
68
  text_color: string | undefined,
69
  background_color: string | undefined,
70
  horizontal_alignment: "LEFT" | "CENTER" | "RIGHT" | undefined,
71
  vertical_alignment: "TOP" | "MIDDLE" | "BOTTOM" | undefined,
72
  wrap_strategy: "OVERFLOW_CELL" | "CLIP" | "WRAP" | undefined,
73
  number_format_type:
74
    | "TEXT"
75
    | "NUMBER"
76
    | "PERCENT"
77
    | "CURRENCY"
78
    | "DATE"
79
    | "TIME"
80
    | "DATE_TIME"
81
    | "SCIENTIFIC"
82
    | undefined,
83
  number_format_pattern: string | undefined
84
) {
85
  const format: { [key: string]: any } = {}
86
  const fields: string[] = []
87
  const textFormat: { [key: string]: any } = {}
88
  for (const [k, v] of Object.entries({
89
    bold,
90
    italic,
91
    underline,
92
    strikethrough,
93
    fontSize: font_size,
94
  })) {
95
    if (v != null) {
96
      textFormat[k] = v
97
      fields.push(`userEnteredFormat.textFormat.${k}`)
98
    }
99
  }
100
  if (text_color) {
101
    textFormat.foregroundColor = color(text_color)
102
    fields.push("userEnteredFormat.textFormat.foregroundColor")
103
  }
104
  if (Object.keys(textFormat).length > 0) format.textFormat = textFormat
105
  if (background_color) {
106
    format.backgroundColor = color(background_color)
107
    fields.push("userEnteredFormat.backgroundColor")
108
  }
109
  for (const [k, v] of Object.entries({
110
    horizontalAlignment: horizontal_alignment,
111
    verticalAlignment: vertical_alignment,
112
    wrapStrategy: wrap_strategy,
113
  })) {
114
    if (v) {
115
      format[k] = v
116
      fields.push(`userEnteredFormat.${k}`)
117
    }
118
  }
119
  if (number_format_type || number_format_pattern) {
120
    format.numberFormat = {
121
      type: number_format_type ?? "NUMBER",
122
      ...(number_format_pattern ? { pattern: number_format_pattern } : {}),
123
    }
124
    fields.push("userEnteredFormat.numberFormat")
125
  }
126
  if (fields.length === 0) throw new Error("Set at least one format attribute")
127

128
  const headers = {
129
    Authorization: `Bearer ${auth.token}`,
130
    Accept: "application/json",
131
  }
132
  const meta = await fetch(
133
    `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}?fields=sheets.properties(sheetId,title)`,
134
    { headers }
135
  )
136
  if (!meta.ok) {
137
    throw new Error(`${meta.status} ${await meta.text()}`)
138
  }
139
  const { sheets } = (await meta.json()) as {
140
    sheets: { properties: { sheetId: number; title: string } }[]
141
  }
142
  const sheet = sheets.find((s) => s.properties.title === sheet_name)
143
  if (!sheet) throw new Error(`Worksheet "${sheet_name}" not found`)
144
  const sheetId = sheet.properties.sheetId
145

146
  const requests = [
147
    {
148
      repeatCell: {
149
        range: gridRange(sheetId, range),
150
        cell: { userEnteredFormat: format },
151
        fields: fields.join(","),
152
      },
153
    },
154
  ]
155

156
  const response = await fetch(
157
    `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheet_id}:batchUpdate`,
158
    {
159
      method: "POST",
160
      headers: { ...headers, "Content-Type": "application/json" },
161
      body: JSON.stringify({ requests }),
162
    }
163
  )
164

165
  if (!response.ok) {
166
    throw new Error(`${response.status} ${await response.text()}`)
167
  }
168

169
  return await response.json()
170
}
171