forked from sheetjs/docs.sheetjs.com
31 lines
935 B
JavaScript
31 lines
935 B
JavaScript
|
import { writeFile, set_fs, utils } from 'xlsx';
|
||
|
import * as fs from 'fs'; set_fs(fs);
|
||
|
import { MongoClient } from 'mongodb';
|
||
|
|
||
|
const url = 'mongodb://localhost:27017/sheetjs';
|
||
|
const db_name = 'sheetjs';
|
||
|
|
||
|
/* Connect to mongodb server */
|
||
|
const client = await MongoClient.connect(url, { useUnifiedTopology: true });
|
||
|
|
||
|
/* Sample data table */
|
||
|
const db = client.db(db_name);
|
||
|
try { await db.collection('pres').drop(); } catch(e) {}
|
||
|
const pres = db.collection('pres');
|
||
|
await pres.insertMany([
|
||
|
{ name: "Barack Obama", idx: 44 },
|
||
|
{ name: "Donald Trump", idx: 45 },
|
||
|
{ name: "Joseph Biden", idx: 46 }
|
||
|
], {ordered: true});
|
||
|
|
||
|
/* Create worksheet from collection */
|
||
|
const aoo = await pres.find({}, {projection:{_id:0}}).toArray();
|
||
|
const ws = utils.json_to_sheet(aoo);
|
||
|
|
||
|
/* Export to XLSX */
|
||
|
const wb = utils.book_new();
|
||
|
utils.book_append_sheet(wb, ws, "Presidents");
|
||
|
writeFile(wb, "SheetJSMongoCRUD.xlsx");
|
||
|
|
||
|
/* Close connection */
|
||
|
client.close();
|