您现在的位置是:网站首页> 编程资料编程资料

Nodejs excel(.xlsx) 文件的读写方式_node.js_

2023-05-24 307人已围观

简介 Nodejs excel(.xlsx) 文件的读写方式_node.js_

Nodejs excel(.xlsx) 文件读写

data.xlsx

名字年龄
张三18
李四19
王五20

获取数据

import xlsx from "xlsx"; const workBook = xlsx.readFile("./data.xlsx");  

获取第一个 execle 工作簿表格

let name = workBook.SheetNames[0] let sheet = workBook.Sheets[name]

1. 输出 json 格式

console.log(xlsx.utils.sheet_to_json(sheet));
[     {         名字:"张三",         年龄:"18"         },     {         名字:"李四",         年龄:"19"     },     {         名字:"王五",         年龄:"20"     } ]

2. 输出 csv 格式

console.log(xlsx.utils.sheet_to_csv(sheet));

名字,年龄,,,,,,,,,,,,,,,,,
张三,18,,,,,,,,,,,,,,,,,
李四,19,,,,,,,,,,,,,,,,,
王五,20,,,,,,,,,,,,,,,,,

3. 输出 html 格式

console.log(xlsx.utils.sheet_to_html(sheet));
SheetJS Table Export
名字年龄
张三18
李四19
王五20

在这里插入图片描述

4.输出 formulae 格式

console.log(xlsx.utils.sheet_to_formulae(sheet));
 [ "A1='名字", "B1='年龄", "A2='张三", 'B2=18', "A3='李四", 'B3=19', "A4='王五", 'B4=20' ]

输出成文件

xlsx.writeFile(workBook, "./output.xlsx");

在这里插入图片描述

全部代码

import xlsx from "xlsx"; const workBook = xlsx.readFile("./data.xlsx"); let name = workBook.SheetNames[0]; let sheet = workBook.Sheets[name]; console.log(xlsx.utils.sheet_to_json(sheet)); console.log(xlsx.utils.sheet_to_csv(sheet)); console.log(xlsx.utils.sheet_to_html(sheet)); console.log(xlsx.utils.sheet_to_formulae(sheet)); xlsx.writeFile(workBook, "./output.xlsx");

方法封装

import xlsx from "xlsx"; /** * 解析 excel 文件成 json 对象 * @param {string} filePath */ export function parseExcel(filePath) { // 读取文件并解析工作簿 const workBook = xlsx.readFile(filePath); // 获取第一个表格 let name = workBook.SheetNames[0]; // 解析表格 return xlsx.utils.sheet_to_json(workBook.Sheets[name]); } /** * 将对象数据解析成 excel * @param {string} filePath 路径 * @param {Array} list 数据 * @param {string} sheetName 表格名字, 默认 Sheet1 */ export function writeExcel(filePath, list, sheetName = "Sheet1") { // 新建工作簿 const workBook = xlsx.utils.book_new(); // 添加表格 xlsx.utils.book_append_sheet(workBook, xlsx.utils.json_to_sheet(list), sheetName); // 输出文件 xlsx.writeFile(workBook, filePath); }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

-六神源码网