Chu Văn Hợp Chu Văn Hợp - 1 year ago 157
Node.js Question

Read data from excel to database in sailsjs

Recently, I try to learn sails.js. Thus I learn it through google and internet, and sails.js is still new, I encountered some trouble while finding any example of reading data from excel (*.xls and *.xlsx files). Can anyone show me how? On google, I found xlsx module (install by

npm install xlsx
) but I still dont know what I have to write in controller and in view files. Thank you a lot!

Answer Source

xlsx will permit you to read a file at the server level, but you're going to have to work on the code to get that data into your views. I can't tell if you're trying to upload files and then read them or just read a static file. At any rate I hope that this is a start as it surely isn't a comprehensive solution.

Here is some example code from one of my scripts that goes down the rows and gets some info from some cells.

var XLSX = require('xlsx'),
    xls_utils = XLSX.utils;

var workbook = XLSX.readFile('./file.xls');
var num_rows = xls_utils.decode_range(sheet['!ref']).e.r;
var sheet = workbook.Sheets[workbook.SheetNames[0]];

for(var i = 0, l = num_rows; i < l; i++){
    // Get cell in {c}olumn 2 (0=1 like arrays) and {r}ow: i
    var cell = xls_utils.encode_cell({c:1, r:i});
    var value = sheet[cell];

    // Do something with value here

You can do a lot more with it and you'll have to play around with it. I find the documentation to be a little rough to get through but the info is all there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download