In enterprise applications, it is often necessary to perform fuzzy queries on tabular data. As a server-side JavaScript running environment, Node.js's powerful processing capabilities allow us to easily perform fuzzy queries in tabular data.
In Node.js, you can use third-party libraries to process tabular data. For example, the most commonly used library is the xlsx
library, which can read tabular data in Excel files and convert it into Save in JSON format. Here we take the xlsx
library as an example to perform table fuzzy query.
First, install the xlsx
library in the Node.js project. You can use the npm command:
npm install xlsx --save
After the installation is complete, we can use xlsx
Library to read table data in Excel files. For example, here is the content of a sample Excel file:
The data in this table has three columns: name, age, and gender. We can read it out through the xlsx
library:
const xlsx = require('xlsx') const workbook = xlsx.readFile('data.xlsx') const sheetname = workbook.SheetNames[0] const worksheet = workbook.Sheets[sheetname] const data = xlsx.utils.sheet_to_json(worksheet) console.log(data)
When reading Excel file data, you need to use the readFile
method, which reads the Excel file as a workbook
object, and then reads the first table Data, finally use the sheet_to_json
method to convert it to JSON format data.
The above code will output the tabular data in data.xlsx
:
[ { 姓名: '张三', 年龄: 25, 性别: '男' }, { 姓名: '李四', 年龄: 30, 性别: '女' }, { 姓名: '王五', 年龄: 28, 性别: '男' }, { 姓名: '赵六', 年龄: 26, 性别: '女' } ]
Next, we can use the filter
method in JavaScript. Fuzzy query. The following code is an example of fuzzy query based on the name column:
const xlsx = require('xlsx') const workbook = xlsx.readFile('data.xlsx') const sheetname = workbook.SheetNames[0] const worksheet = workbook.Sheets[sheetname] const data = xlsx.utils.sheet_to_json(worksheet) const keyword = '李' const result = data.filter(item => item['姓名'].includes(keyword)) console.log(result)
In the above code, a keyword
variable is first defined to store the query keyword. Then use the filter
method in JavaScript to filter out the rows whose names contain keyword
from the table data. includes
The method is used to determine whether a string contains another string. Finally, output the query results.
Running the above code will output the following results:
[ { 姓名: '李四', 年龄: 30, 性别: '女' } ]
Through the above example, we can see that fuzzy queries can be easily performed when using Node.js to process tabular data. Of course, if you need to query multiple columns of data, you can also add multiple judgment conditions to the filter
method. I hope the above content can help you solve the problem of fuzzy query in tables.
The above is the detailed content of How to perform table fuzzy query in nodejs. For more information, please follow other related articles on the PHP Chinese website!