安装
npm i xlsx-populate
代码
import xlsx from "xlsx-populate"
//const xlsx = require("xlsx-populate") 微信小程序一般选这个 根据自己是common还是esm来选择
xlsx.fromBlankAsync().then(workbook=>{
const sheet = workbook.sheet(0) //创建一个sheet
sheet.name("demo") //设置sheet名称
sheet.range("A1:C1").merged(true).value("左右合并实现居中"); //这两行是为了合并单元格
sheet.cell('A1').style({ bold: true, horizontalAlignment: 'center', verticalAlignment: 'center', fontSize: 16 })
sheet.cell("A2").value("单个写值")//单个写值
sheet.range("A3:C3").value("批量写值")//批量写值
sheet.range("A4:A5").merged(true).value("上下合并")//上下合并
const sheet2 = workbook.addSheet("demo2")//添加一个sheet
sheet2.cell("A1").value("单个写值")
workbook.toFileAsync("./demo.xlsx")
})
效果
也可以使用同步方法
import xlsx from "xlsx-populate"
import fs from "node:fs"
const workbook = await xlsx.fromBlankAsync()
const sheet = workbook.sheet(0)
sheet.name("demo")
sheet.cell("A1").value("单个写值")
const sheet2 = workbook.addSheet("demo2")
const xlsxFile = await workbook.outputAsync()
fs.writeFileSync("./output.xlsx", xlsxFile)
效果
读取表格
xlsx.fromFileAsync("./output.xlsx").then(async(workbook) => {
console.log(workbook.sheet("demo").cell("A1").value())//输出 “单个写值”
})