码迷,mamicode.com
首页 > 其他好文 > 详细

node操作excel

时间:2019-11-09 17:33:55      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:pat   write   ssi   public   开始   写入   har   pre   定义   

const xlsx = require(‘xlsx‘);
const path = require(‘path‘)

 读取绝对地址的excel 

let workbook = xlsx.readFile(`./app/public/excel/a1573289191730.xls`); //workbook就是xls文档对象
        let sheetNames = workbook.SheetNames; //获取表明
        let sheet = workbook.Sheets[sheetNames[0]]; //通过表明得到表对象
        var data = xlsx.utils.sheet_to_json(sheet); //通过工具将表对象的数据读出来并转成json
        ctx.body = data

 创建excel并写入数据

 let json = [
            { Name: ‘name_01‘, Age: 11, Address: ‘address_01‘ },
            { Name: ‘name_02‘, Age: 22, Address: ‘address_02‘ },
            { Name: ‘name_03‘, Age: 23, Address: ‘address_03‘ },
            { Name: ‘name_04‘, Age: 24, Address: ‘address_04‘ },
            { Name: ‘name_05‘, Age: 25, Address: ‘address_05‘ },];

        let ss = xlsx.utils.json_to_sheet(json); //通过工具将json转表对象
        let keys = Object.keys(ss).sort(); //排序 [需要注意,必须从A1开始]

        let ref = keys[1] + ‘:‘ + keys[keys.length - 1]; //这个是定义一个字符串 也就是表的范围[A1:C5] 

        let workbook = { //定义操作文档
            SheetNames: [‘nodejs-sheetname‘], //定义表明
            Sheets: {
                ‘nodejs-sheetname‘: Object.assign({}, ss, { ‘!ref‘: ref }) //表对象[注意表明]
            },
        }
        let name = `a${getTime()}.xls`;
        xlsx.writeFile(workbook, `./app/public/excel/${name}`); //将数据写入文件
        ctx.body = `${ctx.origin}/upload/${name}`

未尝试exceljs,下节尝试

const fs = require(‘fs‘)

const Excel = require(‘exceljs‘)

node操作excel

标签:pat   write   ssi   public   开始   写入   har   pre   定义   

原文地址:https://www.cnblogs.com/chenlw/p/11826735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!