Convert JSON data to spreadsheets in multiple formats including Excel, CSV, HTML and many others.
import { write, utils } from "https://cdn.jsdelivr.net/npm/xlsx@0.18.5/+esm"
export const take = () => [
{ type: "json", label: "JSON" },
{ type: "dropdown", label: "Format", options },
]
export const make = ([json, format]) => {
if (!Array.isArray(json)) json = [json]
// Nested objects, arrays and dates are stringified
const rows = json.map((d) =>
Object.fromEntries(
Object.keys(d).map((key) => {
if (typeof d[key] === "object") {
return [key, JSON.stringify(d[key], null, 2)]
} else {
return [key, d[key]]
}
})
)
)
const workbook = utils.book_new()
const worksheet = utils.json_to_sheet(rows)
utils.book_append_sheet(workbook, worksheet, "Sheet1")
const buffer = write(workbook, { bookType: format.bookType, type: "array" })
const value = new Blob([buffer])
const filename = "Spreadsheet" + format.ext
return [
{ type: "file", label: filename, value, filename },
{ type: "table", label: "Preview", value: json },
]
}
const options = [
{
label: "Excel 2007+ XML Format (*.xlsx)",
value: { bookType: "xlsx", ext: ".xlsx" },
},
{
label: "Excel 2007+ Macro XML Format (*.xlsm)",
value: { bookType: "xlsm", ext: ".xlsm" },
},
{
label: "Excel 2007+ Binary Format (*.xlsb)",
value: { bookType: "xlsb", ext: ".xlsb" },
},
{
label: "Excel 97-2004 Workbook Format (*.xls)",
value: { bookType: "biff8", ext: ".xls" },
},
{
label: "Excel 5.0/95 Workbook Format (*.xls)",
value: { bookType: "biff5", ext: ".xls" },
},
{
label: "Excel 4.0 Worksheet Format (*.xls)",
value: { bookType: "biff4", ext: ".xls" },
},
{
label: "Excel 3.0 Worksheet Format (*.xls)",
value: { bookType: "biff3", ext: ".xls" },
},
{
label: "Excel 2.0 Worksheet Format (*.xls)",
value: { bookType: "biff2", ext: ".xls" },
},
{
label: "Excel 2003-2004 SpreadsheetML (*.xls)",
value: { bookType: "xlml", ext: ".xls" },
},
{
label: "OpenDocument Spreadsheet (*.ods)",
value: { bookType: "ods", ext: ".ods" },
},
{
label: "Flat OpenDocument Spreadsheet (*.fods)",
value: { bookType: "fods", ext: ".fods" },
},
{ label: "Lotus Workbook (*.wk3)", value: { bookType: "wk3", ext: ".wk3" } },
{
label: "Comma Separated Values (*.csv)",
value: { bookType: "csv", ext: ".csv" },
},
{
label: "UTF-16 Unicode Text (*.txt)",
value: { bookType: "txt", ext: ".txt" },
},
{
label: "Symbolic Link (*.sylk)",
value: { bookType: "sylk", ext: ".sylk" },
},
{
label: "HTML Document (*.html)",
value: { bookType: "html", ext: ".html" },
},
{
label: "Data Interchange Format (*.dif)",
value: { bookType: "dif", ext: ".dif" },
},
{
label: "dBASE II + VFP Extensions (*.dbf)",
value: { bookType: "dbf", ext: ".dbf" },
},
{ label: "Lotus Worksheet (*.wk1)", value: { bookType: "wk1", ext: ".wk1" } },
{
label: "Rich Text Format (*.rtf)",
value: { bookType: "rtf", ext: ".rtf" },
},
{
label: "Lotus Formatted Text (*.prn)",
value: { bookType: "prn", ext: ".prn" },
},
{
label: "Ethercalc Record Format (*.eth)",
value: { bookType: "eth", ext: ".eth" },
},
]