Skip to content

Instantly share code, notes, and snippets.

@mattbell87
Last active February 24, 2020 07:41
Show Gist options
  • Save mattbell87/f05d67807ed5f411960b8c11719881a5 to your computer and use it in GitHub Desktop.
Save mattbell87/f05d67807ed5f411960b8c11719881a5 to your computer and use it in GitHub Desktop.
Download CouchDB(PouchDB) database documents as excel file
const express = require("express");
const fs = require('fs');
const expressPouchDB = require("express-pouchdb");
const PouchDB = require("pouchdb");
const ExcelJS = require('exceljs');
const moment = require('moment');
const app = express();
const port = 8080;
app.use(express.static("build"));
app.use(express.json());
app.use('/db', expressPouchDB(PouchDB));
app.get('/download/excel/:database', (req, res) => {
let db = new PouchDB(`http://127.0.0.1:${port}/db/${req.params.database}`, { skip_setup: true });
let fields = [];
let header, worksheet, workbook;
db.info().then(() => {
workbook = new ExcelJS.Workbook();
worksheet = workbook.addWorksheet("Results");
header = worksheet.addRow();
return db.allDocs({ 'include_docs': true });
}).then(results => {
fs.writeFileSync("test.json", JSON.stringify(results));
for (let i in results.rows) {
let doc = results.rows[i]['doc'];
delete (doc['_id']);
delete (doc['_rev']);
let row = worksheet.addRow();
//Date field
if (doc.submitted) {
let submitted = moment(doc.submitted);
doc.submitted = submitted.add(submitted.utcOffset(), 'minutes').toDate();
}
for (let field in doc) {
if (fields.indexOf(field) === -1) {
fields.push(field);
}
row.getCell(fields.indexOf(field) + 1).value = doc[field];
}
}
fields.forEach((field, index) => {
let cell = header.getCell(index + 1);
cell.value = field;
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: 'ffcccccc' }
};
cell.font = {
bold: true
}
});
res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
res.setHeader('Content-Disposition', `attachment; filename="${req.params.survey}.xlsx"`)
return workbook.xlsx.write(res);
}).then(() => {
res.end();
}).catch((e) => {
res.status(404);
res.send(e.message);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment