nodejsexpress使⽤node-xlsx实现⽂件的上传下载导⼊导出在express项⽬中使⽤实现⽂件导⼊导出
npm install node-xlsx --save
1. 上传
app.js
const multer  = require('multer')
app.use(multer({dest: './uploads'}).any())
后端接⼝:
const path = require("path")
const fs = require('fs');
const xlsx = require('node-xlsx');
// 接⼝
router.post(
'/importFile',
passport.authenticate('jwt', { session: false }),
(req, res) => {
let excelContent =xlsx.parse(req.files[0].path);
let map = {
'科室名称': 'name',
'所属院区': 'partName',
'上级科室': 'equal',
'科室位置': 'address',
'状态': 'stateName',
}
let partMap = {
'东院': 'EASTPART',
'北院': 'NORTHPART',
'湘南院': 'XIANGNANPART'
};
let stateMap = {
'正常': 0,
'异常': 1
}
let columnName = excelContent[0].data[0];
let data = excelContent[0].data.slice(1);
data.forEach(list => {
let json = {
name: '',
part: '',
partName: '',
equal: '',
state: '',
stateName: '',
};
list.forEach((item, index) => {
let key = map[columnName[index]];
if (key === 'partName') {
json.part = partMap[item];
}
if (key === 'stateName') {
json.state = stateMap[item];
session下载}
json[key] = item;
})
Department.findOne({name: json.name}).then(data => {
Department.findOne({name: json.name}).then(data => {
if (data) {
let j = {...json};
Department.findOneAndUpdate(
{ name: j.name },
{ $set: j},
{ new: true }
).then(r => {
console.log('444444');
})
} else {
new Department(json).save();
}
})
})
res.json({
code: 0,
msg: '导⼊成功',
data: ''
})
}
)
2. 下载
后端接⼝:http:localhost:3000
const path = require("path")
const fs = require('fs');
const xlsx = require('node-xlsx');
// 接⼝
<('/exportFile',
(req,res) => {
Department.find().exec(function(err,data){
var result=[];
var title = ['科室','所属院区','上级科室', '科室位置',]//这是第⼀⾏俗称列名      result.push(title);
let excelPath = solve(__dirname,'../../exportFiles');
data.forEach((item) => {
var itemArr = [];
itemArr.push(item.name);
itemArr.push(item.part);
itemArr.push(item.equal);
itemArr.push(item.address);
result.push(itemArr);
});
var name='科室列表.xlsx';
var buffer=xlsx.build([{name:'sheet1',data:result}]);
fs.writeFile(excelPath+'/' + name,buffer,{'flag':'w'}, err => {
res.download(excelPath+ '/' +name, downerr => {
console.log(downerr, '990909')
});
})
});
});
前端调⽤:
window.location.href = 'localhost:3000/api/department/exportFile'
效果:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。