node的應用方式,導出數據
首先,你要把數據庫連接上,把你要導的數據表寫出來
安裝模塊
$ npm install sequelize $ npm install mysql $ npm install excel-export
引入數據庫
const Sequelize = require('sequelize')
var mysql = new Sequelize('node', 'root', '123456', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 20,
min: 5,
idle: 30000
},
})
module.exports = mysql
引入數據庫表結構
//引入數據庫
const mysql = require('./db_config.js')
const Sequelize = require('sequelize')
//定義表結構
var rizhi = mysql.define('rizhi', {
id: {
primaryKey: true,
type: Sequelize.INTEGER,
},
content: Sequelize.STRING,
summary: Sequelize.STRING,
user: Sequelize.STRING,
day: Sequelize.STRING,
}, {
freezeTableName: true, // Model 對應的表名將與model名相同
timestamps: false
});
//傳值
module.exports = rizhi
獲取表內容
//引入表結構
const rizhi = require('../config/DBConfig.js')
// 列表展示
const hello1 = async function (obj) {
//查詢id大於0的所有內容
let loge = await rizhi.findAll({
where: {
id: { gt: 0},
},
//取消格式化
raw:true
})
return loge
}
//傳出方法
module.exports = {
hello1
}
把表導出其他格式
//引入fs模塊
const fs = require('fs')
//引入excel模塊
var excelPort = require('excel-export');
//引入表內容
const services = require(`../service/LogService`);
const write = function(datas){
//定義一個對象,存放內容
var conf = {};
//定義表頭
conf.cols = [
{caption:'名稱', type:'number', width:20},
{caption:'簡介', type:'string', width:40},
{caption:'報酬', type:'string', width:20},
{caption:'時間', type:'string', width:40},
{caption:'人員', type:'string', width:30},
];
//創建一個數組用來多次遍歷行數據
var array = [];
// 循環導入從數據庫中獲取的表內容
for (var i=0;i<datas.length;i++){
//依次寫入
array[i] = [
datas[i].id,
datas[i].content,
datas[i].summary,
datas[i].user,
datas[i].day
];
}
//寫入道conf對象中
conf.rows = array;
//生成表格
var result = excelPort.execute(conf);
// 定義表格存放路徑
fs.writeFile('util/util.xlsx', result, 'binary',function(err){
if(err){
console.log(err);
}
});
}
//調取數據方法
async function hellos(){
let res = await services.hello1()
// 把數據傳個datas
write(res)
}
//運行方法
hellos()
以上就是node導出excel的方法,提供思考
