0

Create xlsx from JSON

by
Published today

Turn rows (an array of objects) into an .xlsx file written to Windmill object storage, and return its S3 reference. The header row is the union of the rows' keys in first-seen order; nested objects and arrays are written as JSON text. Needs no Microsoft connection and works with any workspace object storage.

Script ms_excel Verified

The script

Submitted by hugo989 Bun
Verified 5 hours ago
1
import * as wmill from "windmill-client"
2
import { S3Object } from "windmill-client"
3
import ExcelJS from "exceljs"
4

5
/**
6
 * Create xlsx from JSON
7
 * Turn rows (an array of objects) into an .xlsx file written to Windmill object storage, and return its S3 reference. The header row is the union of the rows' keys in first-seen order; nested objects and arrays are written as JSON text. Needs no Microsoft connection and works with any workspace object storage.
8
 */
9
export async function main(
10
  rows: { [key: string]: any }[],
11
  destination: S3Object,
12
  sheet_name: string | undefined
13
) {
14
  if (!rows?.length) throw new Error("rows needs at least one object")
15

16
  const workbook = new ExcelJS.Workbook()
17
  const sheet = workbook.addWorksheet(sheet_name || "Sheet1")
18
  const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))]
19
  sheet.columns = keys.map((key) => ({ header: key, key }))
20
  for (const row of rows) {
21
    sheet.addRow(
22
      Object.fromEntries(
23
        Object.entries(row).map(([key, value]) => [
24
          key,
25
          value != null && typeof value === "object" && !(value instanceof Date)
26
            ? JSON.stringify(value)
27
            : value,
28
        ])
29
      )
30
    )
31
  }
32

33
  await wmill.writeS3File(
34
    destination,
35
    new Blob([await workbook.xlsx.writeBuffer()])
36
  )
37
  return destination
38
}
39