Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Json into Xlsx File

I am trying to covert json data into Xlsx file and save it in a folder. I have been trying to use icg-json-to-xlsx module but till now I have been unable to use it. My code looks like this:

jsonXlsx = require('icg-json-to-xlsx');

filename = path.join('./files', "output.xlsx");
outputFile = jsonXlsx(filename, result) //result contains json data
console.log(outputFile);

but I got this error

outputFile = jsonXlsx(filename, result)
             ^
TypeError: Property 'jsonXlsx' of object # is not a function

Getting data from mongodb: in routes:

router.get('/', function(req, res, next) {
  fileController.getAll(function(err, result){
     if(err){
        res.send(500,err);
          }  
       // res.json(result);
        var data = result;

in controller:

FileController.prototype.getAll = function(callback){

File.find( {}, {_id: false, id: true, name: true, status: true}, function(err, file){

    if(err) {
        return callback(err);
    } else {
        if (!file) {
            return callback('file not found');
        }
    }

    callback(null, file);
}
)};
like image 911
ishakya Avatar asked Oct 19 '22 21:10

ishakya


1 Answers

Try this

  outputFile = jsonXlsx.writeFile(filename, result);

jsonXlsx is object, which contains methods like writeFile, writeBuffer, so you can't call jsonXlsx as function... or you need add reference to function like this

jsonXlsxWriteFile = require('icg-json-to-xlsx').writeFile;  
outputFile        = jsonXlsxWriteFile(filename, result)

Example

var jsonXlsx = require('icg-json-to-xlsx');
var path     = require('path');
var filename = path.join('./files', "output.xlsx");


var result = [ 
  { id: '1', name: 'test', status: '123' }, 
  { id: '2', name: 'david', status: '323'}, 
  { id: '3', name: 'ram', status: '2323' } 
];

var outputFile = jsonXlsx.writeFile(filename, JSON.stringify(result));

console.log(outputFile);

Update:

File
  .find({ })
  .select({
    _id: false, id: true, name: true, status: true
  })
  .lean()
  .exec(function(err, file) {
    //
  });

In your case, query returns MongooseDocuments, but jsonXlsx needs plain JavaScript objects, so that's why you should use lean()

like image 163
Oleksandr T. Avatar answered Oct 30 '22 14:10

Oleksandr T.