There are several ways for nodejs to process xlsx files, and the js-xlsx library is used here;
need
There is an xlsx file with several different sheets in it. It is necessary to read the data of different sheets in this table and generate a corresponding json file for each sheet.
For example, there is a template.xlsx
file named , and there are two sheets in it, which are respectively 错误码
, 常见问题
and the contents of these two sheets need to be read separately to generate two files errorCode.json
named . normalQues.json
Inside each json file is an array of objects.
js-xlsx
The article is relatively long, you can directly pull to the end to see the final code.
First, you need to install the xlsx package:
npm install xlsx
The name of the xlsx file used by the text template.xlsx
is as follows:
The process of converting to json file
Import xlsx
and read local files
const xlsx = require("xlsx"); // 想要直接操作本地文件只能采用nodejs的方式,client端无法处理
const workBook = xlsx.readFile("template.xlsx",{
}) // 获取整个xlsx文档
The workBook contains a lot of content and attributes, the following is only a part of the screenshot:
Get the names of all sheets in the xlsx file
console.log(workBook.SheetNames);
Get the contents of all sheets in the xlsx file
cosnole.log(workBook.Sheets);
The sheets obtained in this way are an object containing all sheet contents, and the format is:
Convert to json format
const {
Sheets,SheetNames} = xlsx.readFile("template.xlsx",{
}) // 获取整个xlsx文档
let output = []
SheetNames.forEach(item => {
const arr = xlsx.utils.sheet_to_json(Sheets[item])
output.push(arr)
})
console.log(output)
At this time, you will find that after the output is output, you get an array like this:
This is because xlsx.utils.sheet_to_json
some parameters can be passed in, and different outputs can be controlled through these parameters:
(Image source: js-xlsx uses summary to realize front-end parsing excel )
According to our needs, here, we can add a header to each row of data, and then xlsx.utils.sheet_to_json
add a { header: 2 }
parameter to the function to achieve the desired effect. The effect of different parameters can refer to this article: Research on the header attribute in xlsx.utils.sheet_to_json
So we change the table just now to this, and add a header to it. Note that the header here is the attribute name of each object in the json file generated later.
Add parameters to the code:
const xlsx = require("xlsx"); // 想要直接操作本地文件只能采用nodejs的方式,client端无法处理
const {
Sheets,SheetNames} = xlsx.readFile("template.xlsx",{
}) // 获取整个xlsx文档
let output = []
SheetNames.forEach(item => {
const arr = xlsx.utils.sheet_to_json(Sheets[item],{
header: 2 })
output.push(arr)
})
console.log(output)
The result obtained at this time is as shown in the figure below. It can be seen that a two-dimensional array is generated at this time, the upper part is 错误码
the output of the sheet, and the lower part is 常见问题
the output of the sheet.
Generate JSON file
At this point, the format of the json file is correct, and then we need to put the array corresponding to each sheet into the corresponding json file. You can use fs
the library to generate json files.
const xlsx = require("xlsx"); // 想要直接操作本地文件只能采用nodejs的方式,client端无法处理
const fs = require("fs");
const {
Sheets,SheetNames} = xlsx.readFile("template.xlsx",{
}) // 获取整个xlsx文档
SheetNames.forEach(item => {
const arr = xlsx.utils.sheet_to_json(Sheets[item],{
header: 2 })
let outputFileName = "";
switch (item) {
case "错误码":
outputFileName = "errorCode"
break;
case "常见问题":
outputFileName = "normalQues"
break;
default:
break;
}
//定义输出文件路径
fs.writeFile(`${
outputFileName}.json`, JSON.stringify(arr, '' , ''), (err) => {
if (err) {
console.log(err)
} else {
console.log(`${
outputFileName}.json 创建成功!!!`)
}
})
})
At this time, in the same directory, two corresponding json files are generated, the output we want has been obtained, and the requirement has been realized.
PS: If there is a file with the same name before, or two json files have been generated by running it before, when the code is run again, it will not report an error because the two json files existed before, but will overwrite the contents of the previous file.
additional settings
If you don't want to generate JSON files in the same directory, you can path
set a different directory by:
const path = require("path")
......
//定义输出文件路径
const outputFile = path.join(__dirname, `output/${
outputFileName}.json`)
fs.writeFile(outputFile, JSON.stringify(arr, '' , ''), (err) => {
if (err) {
console.log(err)
} else {
console.log(`output/${
outputFileName}.json 创建成功!!!`)
}
})
But pay the most attention: you must ensure that the output folder exists before running the program, otherwise an error will be reported:
final code
const xlsx = require("xlsx"); // 想要直接操作本地文件只能采用nodejs的方式,client端无法处理
const fs = require("fs");
const path = require("path")
const {
Sheets,SheetNames} = xlsx.readFile("template.xlsx",{
}) // 获取整个xlsx文档
SheetNames.forEach(item => {
const arr = xlsx.utils.sheet_to_json(Sheets[item],{
header: 2 })
let outputFileName = "";
switch (item) {
case "错误码":
outputFileName = "errorCode"
break;
case "常见问题":
outputFileName = "normalQues"
break;
default:
break;
}
//定义输出文件路径
const outputFile = path.join(__dirname, `output/${
outputFileName}.json`)
fs.writeFile(outputFile, JSON.stringify(arr, '' , ''), (err) => {
if (err) {
console.log(err)
} else {
console.log(`output/${
outputFileName}.json 创建成功!!!`)
}
})
})