Hướng dẫn how do you read data from excel file in react js? - làm thế nào để bạn đọc dữ liệu từ tệp excel trong js phản ứng?

Tôi đang cố gắng và đập đầu mình trong khi cố gắng đọc tệp excel trong Reactjs.

Tôi đã thử nhiều thư viện ngoài kia như, SheetJS, Excel-Parser, Exceljs, v.v. (như 8-9) thư viện.

Tôi đang nhận được các lỗi kỳ lạ và khác nhau trong mỗi thư viện.

Ví dụ: tôi đang sử dụng Excel-Parser và nhận lỗi theo dõi

Module not found: 'child_process'

Đó là bởi vì nó là một mô -đun nút và sẽ không hoạt động trong trình duyệt.

Có ai biết một số thư viện tốt và dễ dàng có thể làm việc với ReactJS trong trình duyệt không?reactjs in browser?

Hỏi ngày 24 tháng 10 năm 2017 lúc 11:22Oct 24, 2017 at 11:22

Tôi đã đọc thành công tệp Excel bằng phiên bản NPM của FeetJS XLSX.Sheetjs's npm version xlsx.

Đây là mã:

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f);

Galabra

4.8924 Huy hiệu vàng21 Huy hiệu bạc39 Huy hiệu Đồng4 gold badges21 silver badges39 bronze badges

Đã trả lời ngày 25 tháng 10 năm 2017 lúc 7:18Oct 25, 2017 at 7:18

Noman Alinoman AliNoman Ali

2.9299 Huy hiệu vàng39 Huy hiệu bạc70 Huy hiệu Đồng9 gold badges39 silver badges70 bronze badges

4

Noman Ali! Cảm ơn bạn. Tôi đã sử dụng, mã này
I used, this code

const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) }

Đã trả lời ngày 30 tháng 9 năm 2019 lúc 8:22Sep 30, 2019 at 8:22

YanovyanovYanov

5976 Huy hiệu bạc12 Huy hiệu Đồng6 silver badges12 bronze badges

Tôi thấy xlsx để hoạt động khá tốt. Gói XLSX

Đã trả lời ngày 25 tháng 10 năm 2017 lúc 7:27Oct 25, 2017 at 7:27

rahul_sannrahul_sannrahul_sann

1942 Huy hiệu bạc9 Huy hiệu đồng2 silver badges9 bronze badges

1

const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 3

Đọc các tệp từ nhỏ đến trung bình const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 4 trong trình duyệt hoặc node.js. Phân tích thành JSON với một lược đồ nghiêm ngặt.

Thử nghiệm

Ngoài ra, hãy xem const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 5 để viết các tệp const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 4 đơn giản.

Cài đặt

npm install read-excel-file --save

Nếu bạn không sử dụng Bundler thì hãy sử dụng phiên bản độc lập từ CDN.

Sử dụng

Trình duyệt

<input type="file" id="input" />

import readXlsxFile from 'read-excel-file' const input = document.getElementById('input') input.addEventListener('change', () => { readXlsxFile(input.files[0]).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) })

Lưu ý: Internet Explorer 11 yêu cầu polyfill const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 7. Thí dụ.

Node.js

const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })

Công nhân web

const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })

const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 8

import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }

Json

Để đọc dữ liệu bảng tính và sau đó chuyển đổi nó thành một mảng các đối tượng JSON, hãy truyền tùy chọn const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9 khi gọi npm install read-excel-file --save0. Trong trường hợp đó, thay vì trả lại một loạt các hàng tế bào, nó sẽ trả về một đối tượng hình dạng npm install read-excel-file --save1 trong đó npm install read-excel-file --save2 sẽ là một loạt các đối tượng JSON được tạo từ dữ liệu bảng tính theo const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9 và npm install read-excel-file --save4 sẽ là một mảng của Lỗi gặp phải trong khi chuyển đổi dữ liệu bảng tính sang các đối tượng JSON.

Mỗi thuộc tính của một đối tượng JSON nên được mô tả bởi một "mục" trong const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9. Chìa khóa của mục phải là tiêu đề của cột trong bảng tính. Giá trị của mục nhập phải là một đối tượng có thuộc tính:

  • npm install read-excel-file --save6 - Tên thuộc tính của đối tượng.
  • npm install read-excel-file --save7 - (Tùy chọn) Các thuộc tính bắt buộc có thể được đánh dấu là npm install read-excel-file --save8.
  • npm install read-excel-file --save9 - (Tùy chọn) Hàm xác thực giá trị ô. Chỉ được gọi trên các tế bào không trống. Nếu giá trị ô không hợp lệ, nó sẽ ném lỗi với thông báo lỗi được đặt thành mã lỗi.
  • <input type="file" id="input" />0 - (Tùy chọn) Loại giá trị. Xác định cách giá trị ô sẽ được phân tích cú pháp. Nếu không có <input type="file" id="input" />0 được chỉ định thì giá trị ô được trả về "như là": dưới dạng chuỗi, số, ngày hoặc boolean. A <input type="file" id="input" />0 có thể là:
    • Loại tích hợp:
      • <input type="file" id="input" />3
      • <input type="file" id="input" />4
      • <input type="file" id="input" />5
      • <input type="file" id="input" />6
    • Loại "Tiện ích" được xuất từ ​​thư viện:
      • <input type="file" id="input" />7
      • <input type="file" id="input" />8
      • <input type="file" id="input" />9
    • Loại tùy chỉnh:
      • Một hàm nhận giá trị ô và trả về giá trị phân tích cú pháp. Nếu giá trị không hợp lệ, nó sẽ ném lỗi với thông báo lỗi được đặt thành mã lỗi.

Sidenote: Khi chuyển đổi các giá trị ô thành các thuộc tính đối tượng, theo mặc định, nó bỏ qua tất cả các giá trị import readXlsxFile from 'read-excel-file' const input = document.getElementById('input') input.addEventListener('change', () => { readXlsxFile(input.files[0]).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) })0 (bỏ qua tất cả các ô trống). Đó là cho sự đơn giản. Trong một số trường hợp cạnh, có thể cần phải giữ tất cả các giá trị import readXlsxFile from 'read-excel-file' const input = document.getElementById('input') input.addEventListener('change', () => { readXlsxFile(input.files[0]).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) })0 cho tất cả các ô trống. Ví dụ: đó là trường hợp khi cập nhật dữ liệu trong cơ sở dữ liệu SQL từ bảng tính XLSX sử dụng thư viện ORM phần tiếp theo yêu cầu một thuộc tính phải rõ ràng là import readXlsxFile from 'read-excel-file' const input = document.getElementById('input') input.addEventListener('change', () => { readXlsxFile(input.files[0]).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) })0 để xóa nó trong quá trình hoạt động import readXlsxFile from 'read-excel-file' const input = document.getElementById('input') input.addEventListener('change', () => { readXlsxFile(input.files[0]).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) })3. Để giữ tất cả các giá trị import readXlsxFile from 'read-excel-file' const input = document.getElementById('input') input.addEventListener('change', () => { readXlsxFile(input.files[0]).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) })0, hãy vượt qua tùy chọn import readXlsxFile from 'read-excel-file' const input = document.getElementById('input') input.addEventListener('change', () => { readXlsxFile(input.files[0]).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) })5 khi gọi npm install read-excel-file --save0.

npm install read-excel-file --save4

Nếu có bất kỳ lỗi nào trong khi chuyển đổi dữ liệu bảng tính thành các đối tượng JSON, thuộc tính npm install read-excel-file --save4 được trả về từ hàm sẽ là một mảng không trống. Một yếu tố của thuộc tính npm install read-excel-file --save4 chứa các thuộc tính:

  • const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })0 - Mã lỗi. Ví dụ: const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })1, const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })2.
    • Nếu hàm const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })3 tùy chỉnh được xác định và nó ném const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })4 thì thuộc tính const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })5 sẽ giống như giá trị const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })6.
    • Nếu hàm const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })7 tùy chỉnh được xác định và nó ném const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })4 thì thuộc tính const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })5 sẽ giống như giá trị const readXlsxFile = require('read-excel-file/node') // File path. readXlsxFile('/path/to/file').then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Readable Stream. readXlsxFile(fs.createReadStream('/path/to/file')).then((rows) => { // `rows` is an array of rows // each row being an array of cells. }) // Buffer. readXlsxFile(Buffer.from(fs.readFileSync('/path/to/file'))).then((rows) => { // `rows` is an array of rows // each row being an array of cells. })6.
  • const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })1 - Mã lỗi thứ cấp tùy chọn cung cấp thêm chi tiết về lỗi. Hiện tại, nó chỉ được trả lại cho "tích hợp" <input type="file" id="input" />0s. Ví dụ: const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })3 Đối với const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })4 có nghĩa là "giá trị ô không hợp lệ vì nó không phải là một số".
  • const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })5 - Số hàng trong tệp gốc. const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })6 có nghĩa là hàng đầu tiên, v.v.
  • const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })7 - Tiêu đề cột.
  • const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })8 - Giá trị ô.
  • const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })9 - lược đồ <input type="file" id="input" />0 cho cột này.

Một ví dụ về việc sử dụng const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9

// An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })

Ví dụ <input type="file" id="input" />0 tùy chỉnh. example.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 0

Bỏ qua các hàng trống..

Theo mặc định, nó bỏ qua bất kỳ hàng trống. Để vô hiệu hóa hành vi đó, hãy vượt qua tùy chọn import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }3.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 1

Cách sửa dữ liệu bảng tính trước khi phân tích cú pháp const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9. Ví dụ, làm thế nào để bỏ qua các hàng trống.how to ignore empty rows.

Đôi khi, một bảng tính không chính xác có cấu trúc theo yêu cầu của tính năng phân tích cú pháp const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9 của thư viện này: ví dụ, nó có thể bị thiếu một hàng tiêu đề hoặc chứa một số hàng trình bày hoàn toàn / trống / "rác" hoàn toàn nên được gỡ bỏ. Để khắc phục điều đó, người ta có thể vượt qua chức năng import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }6 tùy chọn sẽ sửa đổi nội dung bảng tính theo yêu cầu.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 2

Chức năng chuyển đổi dữ liệu thành các đối tượng JSON bằng lược đồ cũng được xuất từ ​​thư viện này, nếu có ai muốn nó.function for converting data to JSON objects using a schema is exported from this library too, if anyone wants it.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 3

Một thành phần phản ứng để hiển thị các lỗi xảy ra trong quá trình phân tích/xác thực lược đồ.React component for displaying errors that occured during schema parsing/validation.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 4

JSON (Bản đồ)

Tương tự như trên, nhưng đơn giản hơn: không có bất kỳ phân tích cú pháp hoặc xác nhận.

Đôi khi, một nhà phát triển có thể muốn sử dụng một số giải pháp khác (nâng cao hơn) để phân tích cú pháp và xác nhận lược đồ (như import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }7). Nếu nhà phát triển vượt qua tùy chọn import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }8 thay vì tùy chọn const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9 cho npm install read-excel-file --save0, thì nó sẽ chỉ ánh xạ từng hàng dữ liệu đến đối tượng JSON mà không cần phân tích cú pháp hoặc xác thực. Các giá trị ô sẽ vẫn "như là": như một chuỗi, số, ngày hoặc boolean.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 5

Nhiều tờ

Theo mặc định, nó đọc tờ đầu tiên trong tài liệu. Nếu bạn có nhiều tờ trong bảng tính của mình thì hãy chuyển một số trang (bắt đầu từ const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })6) hoặc tên trang tính trong đối số // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })2.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 6

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 7

Theo mặc định, // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })3 là const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })6.

Để có được tên của tất cả các tờ, hãy sử dụng hàm // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })5:

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 8

ngày

Định dạng XLSX ban đầu không có loại "ngày" chuyên dụng, do đó ngày trong hầu hết các trường hợp được lưu trữ đơn giản là số (số ngày kể từ // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })6) cùng với mô tả "định dạng" (như // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })7) hướng dẫn phần mềm xem bảng tính để định dạng ngày trong ô bằng cách sử dụng định dạng nhất định đó.

Khi sử dụng // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })8 với tham số const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9, tất cả các cột lược đồ có loại <input type="file" id="input" />6 được phân tích điện tử tự động là ngày. Khi sử dụng // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })8 mà không có tham số const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9, thư viện này cố gắng đoán xem một ô có chứa một ngày hay chỉ là một số bằng cách kiểm tra "định dạng" của ô-nếu "định dạng" là một trong các định dạng ngày tích hợp thì các giá trị của các ô như vậy được tự động phân tích cú pháp là ngày. Trong các trường hợp khác, khi các ô ngày sử dụng định dạng không được xây dựng (như import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 03), người ta có thể truyền tham số import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 04 rõ ràng để hướng dẫn thư viện phân tích các ô số có "định dạng" như ngày:

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 9

Cắt

Theo mặc định, nó tự động cắt tất cả các giá trị chuỗi. Để tắt tính năng này, hãy vượt qua tùy chọn import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 05.

const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 0

Biến đổi

Đôi khi, một bảng tính không chính xác có cấu trúc theo yêu cầu của tính năng phân tích cú pháp const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9 của thư viện này: ví dụ, nó có thể bị thiếu một hàng tiêu đề hoặc chứa một số hàng trình bày hoàn toàn / trống / "rác" hoàn toàn nên được gỡ bỏ. Để khắc phục điều đó, người ta có thể vượt qua chức năng import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }6 tùy chọn sẽ sửa đổi nội dung bảng tính theo yêu cầu.

import * as XLSX from 'xlsx'; //f = file var name = f.name; const reader = new FileReader(); reader.onload = (evt) => { // evt = on_file_select event /* Parse data */ const bstr = evt.target.result; const wb = XLSX.read(bstr, {type:'binary'}); /* Get first worksheet */ const wsname = wb.SheetNames[0]; const ws = wb.Sheets[wsname]; /* Convert array of arrays */ const data = XLSX.utils.sheet_to_csv(ws, {header:1}); /* Update state */ console.log("Data>>>"+data); }; reader.readAsBinaryString(f); 2

Chức năng chuyển đổi dữ liệu thành các đối tượng JSON bằng lược đồ cũng được xuất từ ​​thư viện này, nếu có ai muốn nó.

Một thành phần phản ứng để hiển thị các lỗi xảy ra trong quá trình phân tích/xác thực lược đồ.

JSON (Bản đồ)

Tương tự như trên, nhưng đơn giản hơn: không có bất kỳ phân tích cú pháp hoặc xác nhận.

Đôi khi, một nhà phát triển có thể muốn sử dụng một số giải pháp khác (nâng cao hơn) để phân tích cú pháp và xác nhận lược đồ (như import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }7). Nếu nhà phát triển vượt qua tùy chọn import readXlsxFile from 'read-excel-file/web-worker' onmessage = function(event) { readXlsxFile(event.data).then((rows) => { // `rows` is an array of rows // each row being an array of cells. postMessage(rows) }) }8 thay vì tùy chọn const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 9 cho npm install read-excel-file --save0, thì nó sẽ chỉ ánh xạ từng hàng dữ liệu đến đối tượng JSON mà không cần phân tích cú pháp hoặc xác thực. Các giá trị ô sẽ vẫn "như là": như một chuỗi, số, ngày hoặc boolean.

Nhiều tờ

Theo mặc định, nó đọc tờ đầu tiên trong tài liệu. Nếu bạn có nhiều tờ trong bảng tính của mình thì hãy chuyển một số trang (bắt đầu từ const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })6) hoặc tên trang tính trong đối số // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })2.

Theo mặc định, // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })3 là const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })6.

Để có được tên của tất cả các tờ, hãy sử dụng hàm // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })5:

const handleUpload = (e) => { e.preventDefault(); var files = e.target.files, f = files[0]; var reader = new FileReader(); reader.onload = function (e) { var data = e.target.result; let readedData = XLSX.read(data, {type: 'binary'}); const wsname = readedData.SheetNames[0]; const ws = readedData.Sheets[wsname]; /* Convert array to json*/ const dataParse = XLSX.utils.sheet_to_json(ws, {header:1}); setFileUploaded(dataParse); }; reader.readAsBinaryString(f) } 2

Nhiều tờ

Theo mặc định, nó đọc tờ đầu tiên trong tài liệu. Nếu bạn có nhiều tờ trong bảng tính của mình thì hãy chuyển một số trang (bắt đầu từ const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })6) hoặc tên trang tính trong đối số // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })2.

Theo mặc định, // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })3 là const worker = new Worker('web-worker.js') worker.onmessage = function(event) { // `event.data` is an array of rows // each row being an array of cells. console.log(event.data) } worker.onerror = function(event) { console.error(event.message) } const input = document.getElementById('input') input.addEventListener('change', () => { worker.postMessage(input.files[0]) })6.

Để có được tên của tất cả các tờ, hãy sử dụng hàm // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })5:

ngày

Định dạng XLSX ban đầu không có loại "ngày" chuyên dụng, do đó ngày trong hầu hết các trường hợp được lưu trữ đơn giản là số (số ngày kể từ // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })6) cùng với mô tả "định dạng" (như // An example *.xlsx document: // ----------------------------------------------------------------------------------------- // | START DATE | NUMBER OF STUDENTS | IS FREE | COURSE TITLE | CONTACT | STATUS | // ----------------------------------------------------------------------------------------- // | 03/24/2018 | 10 | true | Chemistry | (123) 456-7890 | SCHEDULED | // ----------------------------------------------------------------------------------------- const schema = { 'START DATE': { // JSON object property name. prop: 'date', type: Date }, 'NUMBER OF STUDENTS': { prop: 'numberOfStudents', type: Number, required: true }, // Nested object example. // 'COURSE' here is not a real Excel file column name, // it can be any string — it's just for code readability. 'COURSE': { // Nested object path: `row.course` prop: 'course', // Nested object schema: type: { 'IS FREE': { prop: 'isFree', type: Boolean }, 'COURSE TITLE': { prop: 'title', type: String } } }, 'CONTACT': { prop: 'contact', required: true, // A custom `type` can be defined. // A `type` function only gets called for non-empty cells. type: (value) => { const number = parsePhoneNumber(value) if (!number) { throw new Error('invalid') } return number } }, 'STATUS': { prop: 'status', type: String, oneOf: [ 'SCHEDULED', 'STARTED', 'FINISHED' ] } } readXlsxFile(file, { schema }).then(({ rows, errors }) => { // `errors` list items have shape: `{ row, column, error, reason?, value?, type? }`. errors.length === 0 rows === [{ date: new Date(2018, 2, 24), numberOfStudents: 10, course: { isFree: true, title: 'Chemistry' }, contact: '+11234567890', status: 'SCHEDULED' }] })7) hướng dẫn phần mềm xem bảng tính để định dạng ngày trong ô bằng cách sử dụng định dạng nhất định đó.

Giấy phép

MIT

Làm thế nào đọc dữ liệu từ Excel trong JavaScript?

Dự án JS, tức là, bên trong chỉ số. Tệp JS. Bây giờ, chúng tôi sẽ tạo một hàm parseExcel (), sẽ lấy tên tệp tệp làm tham số và trả về một mảng các đối tượng. Bây giờ chúng ta có tên tệp Excel, chúng ta có thể đọc và trích xuất tất cả thông tin từ tệp đó bằng hàm ReadFile của gói XLSX.

Làm cách nào để hiển thị một tệp excel trong React?

Sử dụng nhập excel-excel-render {outtable, excelrenderer} từ 'React-excel-renderer';Đặt một phần tử đầu vào đơn giản trong hàm kết xuất của lớp của bạn và chuyển một trình xử lý onchange. import {OutTable, ExcelRenderer} from 'react-excel-renderer'; Place a simple input element in the render function of your class and pass an onChange handler.

Làm thế nào để bạn có được dữ liệu từ Excel ở định dạng JSON trong ReactJS?

log ("Dữ liệu >>>" + dữ liệu); // cho thấy dữ liệu Excel được đọc bảng điều khiển.đăng nhập (điều này. ConvertTojson (dữ liệu));// hiển thị dữ liệu ở định dạng JSON};người đọc.ReadasbinaryString (F);} convertTojson (csv) {var lines = csv.

Làm cách nào để đọc bảng tính excel?

Để đọc một bảng tính khác nhau, chọn bảng tính từ danh sách.Bạn cũng có thể đọc một loạt các ô.Sử dụng cùng một phương thức để chỉ định phạm vi ô như bạn làm trong Excel.Ví dụ: A1: D10.select the worksheet from the list. You can also read a range of cells. Use the same method for specifying cell ranges as you would in Excel. For example: A1:D10.

Chủ đề