Чтение файла Excel с помощью node.js
Хорошо, поэтому я использую модуль FileUploader
для загрузки моего файла из angular в мой REST API
:
var uploader = $scope.uploader = new FileUploader({
url: api.getUrl('uploadCompetence',null)
});
Это отправляется следующей функции POST
:
router.route('/api/uploadCompetence')
.post(function (req, res) {
// This is where i want to read the file
var competence = Competence.build(req.body.location);
competence.add(function (success) {
res.json({message: 'quote created!'});
},
function (err) {
res.status(err).send(err);
});
})
Теперь моя цель - прочитать файл excel
, а затем добавить каждую строку в мою базу данных.
Однако я не совсем уверен, как я могу прочитать файл из Node.js
Я отлаживал свой сервер и не мог найти файл в любом месте, но api вызывается из моего приложения Angular
Может ли кто-нибудь подтолкнуть меня в правильном направлении?:)
Ответы
Ответ 1
Существует несколько разных библиотек, обрабатывающих файлы Excel (.xlsx). Я перечислил два проекта, которые мне интересны и интересны.
Node -xlsx
Анализатор и построитель Excel. Это своего рода оболочка для популярного проекта JS-XLSX, который является чистой реализацией javascript из спецификации Office Open XML.
Node страница проекта -xlsx
Пример для анализа файла
var xlsx = require('node-xlsx');
var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file
var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer
ExcelJS
Чтение, управление и запись данных и стилей таблиц в XLSX и JSON. Это активный проект. На момент написания последнего коммита было 9 часов назад. Я не тестировал это сам, но api выглядит обширным с множеством возможностей.
страница проекта exceljs
Пример кода:
// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
.then(function() {
// use workbook
});
// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());
Ответ 2
Вы также можете использовать этот модуль узла с именем js-xlsx
1) Установить модуль
npm install xlsx
2) Модуль импорта + фрагмент кода
var XLSX = require('xlsx')
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
console.log(xlData);
Ответ 3
установите exceljs и используйте следующий код,
var Excel = require('exceljs');
var wb = new Excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'sample.xlsx');
wb.xlsx.readFile(filePath).then(function(){
var sh = wb.getWorksheet("Sheet1");
sh.getRow(1).getCell(2).value = 32;
wb.xlsx.writeFile("sample2.xlsx");
console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);
console.log(sh.rowCount);
//Get all the rows data [1st and 2nd column]
for (i = 1; i <= sh.rowCount; i++) {
console.log(sh.getRow(i).getCell(1).value);
console.log(sh.getRow(i).getCell(2).value);
}
});
Ответ 4
Полезная ссылка
https://ciphertrick.com/read-excel-files-convert-json-node-js/
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var xlstojson = require("xls-to-json-lc");
var xlsxtojson = require("xlsx-to-json-lc");
app.use(bodyParser.json());
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
}
});
var upload = multer({ //multer settings
storage: storage,
fileFilter : function(req, file, callback) { //file filter
if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
return callback(new Error('Wrong extension type'));
}
callback(null, true);
}
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
var exceltojson;
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
/** Multer gives us file info in req.file object */
if(!req.file){
res.json({error_code:1,err_desc:"No file passed"});
return;
}
/** Check the extension of the incoming file and
* use the appropriate module
*/
if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
exceltojson = xlsxtojson;
} else {
exceltojson = xlstojson;
}
try {
exceltojson({
input: req.file.path,
output: null, //since we don't need output.json
lowerCaseHeaders:true
}, function(err,result){
if(err) {
return res.json({error_code:1,err_desc:err, data: null});
}
res.json({error_code:0,err_desc:null, data: result});
});
} catch (e){
res.json({error_code:1,err_desc:"Corupted excel file"});
}
})
});
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.listen('3000', function(){
console.log('running on 3000...');
});
Ответ 5
Установите модуль 'spread_sheet' node, он будет добавлять и выбирать строку из локальной таблицы