Nodejs 创建文本文件和Excel文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xubuhang/article/details/78595549

需要引入依赖模块fs和excel

npm install fs 
npm install json2excel

fs 创建文件模块

json2excel  json转ecxel


这是一个简单Demo,nodejs服务器启动时候就生成output.txt和j2x.xlsx

实现代码

const http = require('http');
var fs = require('fs');
var path = require('path');
var jexcel=require('json2excel');
var sheet1={
    header: {
        'author': 'Author Name',
        'title': 'Article Title'
    },
    items: [
        {
            author:'john',
            title:'how to use this'
        },
        {
            author:'Bob',
            title:'so Easy'
        }
    ],
    sheetName: 'sheet1'  //
};

var data = {
    sheets: [sheet1],
    filepath: path.join(path.resolve(__dirname, '../..'),"xls/j2x.xlsx")
}
const hostname = '0.0.0.0';
const port = 3003;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);

fs.writeFile(path.join(path.resolve(__dirname, '../..'),"xls/output.txt"), "Hello World!", function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("File saved successfully!");
});


jexcel.j2e(data,function(err){
    console.log('finish')
});
});




运行命令

扫描二维码关注公众号,回复: 4680220 查看本文章
node /Users/admin/Downloads/test/main/engin/example.js 


__dirname 当前代码路径
 
 
path.resolve(__dirname, '../..') 上上级文件路径
path.join(__dirname,"xls/output.txt") 当前路径下的路径,连接路径



猜你喜欢

转载自blog.csdn.net/xubuhang/article/details/78595549