node-xlsx代码记录

本文介绍了一种使用Node.js进行Excel文件读写的方法,通过node-xlsx库解析和生成Excel文件,提供了读取指定目录下所有.xlsx文件名、读取Excel数据、按需处理表格数据并写回新文件的实用函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 原文连接:https://blog.youkuaiyun.com/cvchihzhza/article/details/86549094

const xlsx = require('node-xlsx')
const fs = require('fs')
const join = require('path').join
 
/**
 * 获取路径下以extname结尾的文件名,返回文件名数组
 * @param {*} path 
 * @param {*} extname 
 */
function readAllFileName(path, extname) {
    let out = []
    let files = fs.readdirSync(path)
    let reg = new RegExp(extname)
    files.forEach((item) => {
        let filePath = join(path, item)
        if (reg.test(filePath)) {
            out.push(item)
        }
    })
    return out
}
 
function readExcel(fileName) {
    return xlsx.parse(fileName)
}
/**
 * 
 * @param {*} excel 
 * @param {*} n 1对应Sheet1 
 * @param {*} isNeedFirstRow 
 */
function readSheet(excel, n, isNeedFirstRow) {
    let sheet = excel[n - 1].data
    if (!isNeedFirstRow) sheet.shift()  //去除第一行
    return sheet
}
 
function writeExcel(sheet, fileName, sheetName) {
 
    let buffer = xlsx.build([
        { name: sheetName, data: sheet }
    ])
 
    fs.writeFile(fileName, buffer, function (err) {
        if (err) throw err;
        console.log('Write to excel has successed');
    })
}
 
let fileNames = readAllFileName('./', '.xlsx')
let fileName = fileNames[0]
let excel = readExcel(fileName)
let sheet1 = readSheet(excel, 1, true)
 
writeExcel(out, '2.xlsx','sheet1')

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值