Xin chào các nhà phát triển 🙌
Hôm nay chúng ta sẽ xem cách chuyển đổi Excel sang JSON
Chúng tôi sẽ sử dụng gói xlsx
Không nói nhiều nữa, hãy chuyển sang phần mã hóa
Cài đặt gói xlsx
npm i xlsx
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Tạo cấu trúc cơ bản để tải tệp lên
Upload File
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Chuyển đổi tệp Excel sang JSON
const readUploadFile = [e] => {
e.preventDefault[];
if [e.target.files] {
const reader = new FileReader[];
reader.onload = [e] => {
const data = e.target.result;
const workbook = xlsx.read[data, { type: "array" }];
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const json = xlsx.utils.sheet_to_json[worksheet];
console.log[json];
};
reader.readAsArrayBuffer[e.target.files[0]];
}
}
Vào chế độ toàn màn hình Thoát chế độ toàn màn hình
Kaboom. 🔥 chỉ với hai bước đơn giản, bạn có thể chuyển đổi Excel sang JSON
HappyCoding
Chốt tại đây 👋👋👋
Đây là Shareef
dự án gần đây của tôi youounotes
Danh mục đầu tư của tôi
Twitter ShareefBhai99
liên kết
Các Blog khác của tôi
Đôi khi trong một ứng dụng, bạn có thể có yêu cầu tải dữ liệu lên qua tệp excel hoặc công việc đọc dữ liệu từ một loạt tệp excel hoặc có thể chạy một số phân tích. Xử lý các tệp excel là phổ biến trong các ứng dụng web. Hướng dẫn này nhằm mục đích giúp các nhà phát triển đọc các tệp excel bằng NodeJS dễ dàng hơn
Sau hướng dẫn này, bạn sẽ có thể tải tệp excel trên ứng dụng của mình lên một đường dẫn cụ thể, đọc tệp và chuyển đổi nó thành dữ liệu json và sau đó, rõ ràng là bạn có thể làm bất cứ điều gì bạn muốn với dữ liệu hợp lý có lập trình đó
Chúng tôi sẽ xử lý hai định dạng tệp excel. Đó là chuyển đổi ‘. xls' thành json và '. xlsx' sang json
lộ trìnhỞ đây chúng tôi sẽ làm những điều sau đây
- Thiết lập máy chủ và tuyến đường của Node express
- Tải tệp lên, sử dụng Multer
- Đọc và chuyển excel sang json
Ghi chú. Phần bên dưới đề cập đến việc tải thêm các tệp lên, nếu không bắt buộc, bạn có thể trực tiếp bỏ qua phần Đọc và chuyển đổi excel sang json bên dưới
TẢI XUỐNG
Thiết lập máy chủ Express và Multer để tải lênChúng tôi đã thực hiện một hướng dẫn về Tải lên tệp, liên quan đến việc thiết lập nút-express cùng với bộ trộn để tải lên, trong đó chúng tôi đã giải thích chi tiết từng bước. Đối với hướng dẫn này thay vì lặp lại điều tương tự, chúng tôi sẽ chọn các phần mã từ đó. Vui lòng đọc phần hướng dẫn được đề cập bên dưới để được giải thích chi tiết
Điều hướng vào thư mục làm việc của bạn thông qua bảng điều khiển của bạn và chạy các lệnh sau
npm init --yes
npm install express --save
npm install multer --save
npm install body-parser --save
mkdir uploads
touch app.js
Bây giờ tôi sẽ chọn mã từ hướng dẫn tải lên tệp và thêm nó vào ứng dụng của mình. js. Đồng thời, chúng tôi sẽ loại bỏ các khối mã không mong muốn
ứng dụng. js
var express = require['express'];
var app = express[];
var bodyParser = require['body-parser'];
var multer = require['multer'];
app.use[bodyParser.json[]];
var storage = multer.diskStorage[{ //multers disk storage settings
destination: function [req, file, cb] {
cb[null, './uploads/']
},
filename: function [req, file, cb] {
var datetimestamp = Date.now[];
cb[null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split['.'][file.originalname.split['.'].length -1]]
}
}];
var upload = multer[{ //multer settings
storage: storage
}].single['file'];
/** API path that will upload the files */
app.post['/upload', function[req, res] {
upload[req,res,function[err]{
if[err]{
res.json[{error_code:1,err_desc:err}];
return;
}
res.json[{error_code:0,err_desc:null}];
}];
}];
app.get['/',function[req,res]{
res.sendFile[__dirname + "/index.html"];
}];
app.listen['3000', function[]{
console.log['running on 3000...'];
}];
Chỉ cần giải thích nhanh về đoạn mã trên, trước tiên chúng tôi yêu cầu các mô-đun khác nhau, chúng tôi sẽ cần trình phân tích cú pháp nội dung để phân tích dữ liệu bài đăng. Tiếp theo, chúng tôi đang thiết lập cài đặt lưu trữ của bộ lọc, cho đích lưu trữ, tên tệp đã tải lên và cả loại lưu trữ dưới dạng lưu trữ đĩa. Bên dưới nó, là các cài đặt cho multer và hơn nữa, chúng tôi đã thêm tuyến/đường dẫn tốc hành nơi chúng tôi sẽ tải tệp lên
Chúng tôi cũng có một chỉ số đơn giản. tệp html được hiển thị tại đường dẫn gốc. mục lục. html không là gì ngoài một hình thức mà chúng tôi sẽ có thể tải lên các tệp của mình. Cuối cùng, chúng tôi đang lắng nghe cổng 3000 để khởi động máy chủ nút
mục lục. html
Upload
Bây giờ nếu bạn chạy ứng dụng của mình, bạn sẽ có thể tải bất kỳ tệp nào lên thư mục tải lên của chúng tôi. Nhưng chúng tôi cần hạn chế ứng dụng của mình chỉ cho phép các tệp excel i. e [. xl,. xlsx]
Thêm bộ lọc loại tệpChúng tôi sẽ thay đổi chức năng tải lên của mình để chỉ cho phép tệp excel bằng cách thêm tùy chọn bộ lọc tệp do Multer cung cấp
ứng dụng. js
var upload = multer[{ //multer settings
storage: storage,
fileFilter : function[req, file, callback] { //file filter
if [['xls', 'xlsx'].indexOf[file.originalname.split['.'][file.originalname.split['.'].length-1]] === -1] {
return callback[new Error['Wrong extension type']];
}
callback[null, true];
}
}].single['file'];
Đọc và chuyển excel sang jsonBây giờ, chúng tôi có thể tải tệp lên máy chủ của mình và chúng tôi đã thêm xác thực tiện ích mở rộng. Thử thách tiếp theo là đọc tệp đã tải lên và chuyển đổi nó thành json
Để làm điều này, chúng tôi sẽ sử dụng hai mô-đun nút, xls-to-json-lc và xlsx-to-json-lc để chuyển đổi. xls sang jsonand. xlsx đến json tương ứng
Cài đặt chúng bằng cách chạy các lệnh dưới đây
npm install xlsx-to-json-lc --save
npm install xls-to-json-lc --save
Cách sử dụng
________số 8_______Thực hiện
Hãy nhớ rằng chúng tôi có hai mô-đun nút khác nhau cho hai phần mở rộng excel. Trước tiên, chúng tôi sẽ kiểm tra phần mở rộng của tệp đến và sau đó tùy thuộc vào nó, chúng tôi sẽ sử dụng đúng mô-đun. Hãy để chúng tôi bắt đầu
Bắt đầu bằng cách yêu cầu các mô-đun của chúng tôi vào ứng dụng của chúng tôi. js
ứng dụng. js
var xlstojson = require["xls-to-json-lc"];
var xlsxtojson = require["xlsx-to-json-lc"];
Hãy thay đổi đường dẫn /upload của chúng ta
ứng dụng. js [/đường dẫn tải lên]
/** API path that will upload the files */
app.post['/upload', function[req, res] {
var exceltojson; //Initialization
upload[req,res,function[err]{
if[err]{
res.json[{error_code:1,err_desc:err}];
return;
}
/** Multer gives us file info in req.file object */
if[!req.file]{
res.json[{error_code:1,err_desc:"No file passed"}];
return;
}
//start convert process
/** Check the extension of the incoming file and
* use the appropriate module
*/
if[req.file.originalname.split['.'][req.file.originalname.split['.'].length-1] === 'xlsx']{
exceltojson = xlsxtojson;
} else {
exceltojson = xlstojson;
}
try {
exceltojson[{
input: req.file.path, //the same path where we uploaded our file
output: null, //since we don't need output.json
lowerCaseHeaders:true
}, function[err,result]{
if[err] {
return res.json[{error_code:1,err_desc:err, data: null}];
}
res.json[{error_code:0,err_desc:null, data: result}];
}];
} catch [e]{
res.json[{error_code:1,err_desc:"Corupted excel file"}];
}
}];
}];
Chúng tôi sẽ nhận được dữ liệu đã chuyển đổi của mình trong biến kết quả [i. e tham số thứ hai]. Vậy là xong, bây giờ chúng ta đã sẵn sàng để chạy và dùng thử ứng dụng của mình
Các tệp cuối cùng của chúng tôi trông như thế này
ứng dụng. js
var express = require['express'];
var app = express[];
var bodyParser = require['body-parser'];
var multer = require['multer'];
var xlstojson = require["xls-to-json-lc"];
var xlsxtojson = require["xlsx-to-json-lc"];
app.use[bodyParser.json[]];
var storage = multer.diskStorage[{ //multers disk storage settings
destination: function [req, file, cb] {
cb[null, './uploads/']
},
filename: function [req, file, cb] {
var datetimestamp = Date.now[];
cb[null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split['.'][file.originalname.split['.'].length -1]]
}
}];
var upload = multer[{ //multer settings
storage: storage,
fileFilter : function[req, file, callback] { //file filter
if [['xls', 'xlsx'].indexOf[file.originalname.split['.'][file.originalname.split['.'].length-1]] === -1] {
return callback[new Error['Wrong extension type']];
}
callback[null, true];
}
}].single['file'];
/** API path that will upload the files */
app.post['/upload', function[req, res] {
var exceltojson;
upload[req,res,function[err]{
if[err]{
res.json[{error_code:1,err_desc:err}];
return;
}
/** Multer gives us file info in req.file object */
if[!req.file]{
res.json[{error_code:1,err_desc:"No file passed"}];
return;
}
/** Check the extension of the incoming file and
* use the appropriate module
*/
if[req.file.originalname.split['.'][req.file.originalname.split['.'].length-1] === 'xlsx']{
exceltojson = xlsxtojson;
} else {
exceltojson = xlstojson;
}
try {
exceltojson[{
input: req.file.path,
output: null, //since we don't need output.json
lowerCaseHeaders:true
}, function[err,result]{
if[err] {
return res.json[{error_code:1,err_desc:err, data: null}];
}
res.json[{error_code:0,err_desc:null, data: result}];
}];
} catch [e]{
res.json[{error_code:1,err_desc:"Corupted excel file"}];
}
}]
}];
app.get['/',function[req,res]{
res.sendFile[__dirname + "/index.html"];
}];
app.listen['3000', function[]{
console.log['running on 3000...'];
}];
bưu kiện. json
{
"name": "excelupload",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Rahil Shaikh",
"license": "ISC",
"dependencies": {
"body-parser": "1.15.1",
"express": "4.13.4",
"multer": "1.1.0",
"xls-to-json-lc": "0.3.3",
"xlsx-to-json-lc": "0.2.5"
}
}
Chạy ứng dụngĐể chạy ứng dụng, chỉ cần điều hướng vào thư mục woking của bạn bằng công cụ dòng lệnh và chạy
var express = require['express'];
var app = express[];
var bodyParser = require['body-parser'];
var multer = require['multer'];
app.use[bodyParser.json[]];
var storage = multer.diskStorage[{ //multers disk storage settings
destination: function [req, file, cb] {
cb[null, './uploads/']
},
filename: function [req, file, cb] {
var datetimestamp = Date.now[];
cb[null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split['.'][file.originalname.split['.'].length -1]]
}
}];
var upload = multer[{ //multer settings
storage: storage
}].single['file'];
/** API path that will upload the files */
app.post['/upload', function[req, res] {
upload[req,res,function[err]{
if[err]{
res.json[{error_code:1,err_desc:err}];
return;
}
res.json[{error_code:0,err_desc:null}];
}];
}];
app.get['/',function[req,res]{
res.sendFile[__dirname + "/index.html"];
}];
app.listen['3000', function[]{
console.log['running on 3000...'];
}];
0Bản demo và thiết lập nhanh[. [bản demo excel to json][http. //i0. wp. com/mã. mật mã. com/wp-content/uploads/sites/3/2016/06/demo-gif. gif?resize=710%2C331]][http. //i0. wp. com/mã. mật mã. com/wp-content/uploads/sites/3/2016/06/demo-gif. gif] excel sang bản demo json
Để nhanh chóng chạy ứng dụng, hãy làm theo các bước dưới đây
var express = require['express'];
var app = express[];
var bodyParser = require['body-parser'];
var multer = require['multer'];
app.use[bodyParser.json[]];
var storage = multer.diskStorage[{ //multers disk storage settings
destination: function [req, file, cb] {
cb[null, './uploads/']
},
filename: function [req, file, cb] {
var datetimestamp = Date.now[];
cb[null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split['.'][file.originalname.split['.'].length -1]]
}
}];
var upload = multer[{ //multer settings
storage: storage
}].single['file'];
/** API path that will upload the files */
app.post['/upload', function[req, res] {
upload[req,res,function[err]{
if[err]{
res.json[{error_code:1,err_desc:err}];
return;
}
res.json[{error_code:0,err_desc:null}];
}];
}];
app.get['/',function[req,res]{
res.sendFile[__dirname + "/index.html"];
}];
app.listen['3000', function[]{
console.log['running on 3000...'];
}];
1Xóa tệp đã tải lênTrong một số trường hợp, bạn có thể không muốn giữ lại tệp excel đã tải lên trên máy chủ. Đây là một đoạn mã để xóa các tệp đã tải lên ngay khi chúng được chuyển đổi
bưu kiện. json
var express = require['express'];
var app = express[];
var bodyParser = require['body-parser'];
var multer = require['multer'];
app.use[bodyParser.json[]];
var storage = multer.diskStorage[{ //multers disk storage settings
destination: function [req, file, cb] {
cb[null, './uploads/']
},
filename: function [req, file, cb] {
var datetimestamp = Date.now[];
cb[null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split['.'][file.originalname.split['.'].length -1]]
}
}];
var upload = multer[{ //multer settings
storage: storage
}].single['file'];
/** API path that will upload the files */
app.post['/upload', function[req, res] {
upload[req,res,function[err]{
if[err]{
res.json[{error_code:1,err_desc:err}];
return;
}
res.json[{error_code:0,err_desc:null}];
}];
}];
app.get['/',function[req,res]{
res.sendFile[__dirname + "/index.html"];
}];
app.listen['3000', function[]{
console.log['running on 3000...'];
}];
2Sử dụng mã này ngay bên dưới chuyển đổi excel sang json. yêu cầu. tài liệu. đường dẫn sẽ đề cập đến tệp hiện được tải lên
Phần kết luậnExcel to json là một yêu cầu thường xuyên đối với các ứng dụng web. Hướng dẫn này giải thích cách dễ dàng thực hiện trong Node. js