Hướng dẫn how to import data from excel to javascript - cách nhập dữ liệu từ excel sang javascript

Tôi có một plunker đính kèm theo đây. http://plnkr.co/edit/rkucchxd6ughotclmdfj?p=preview

Tôi có thể nhập một tệp văn bản đúng cách mà không có bất kỳ lỗi nào. Tuy nhiên, khi tôi cố gắng nhập một tệp Excel, nó sẽ nhập các giá trị chữ và số ngẫu nhiên và dữ liệu không liên quan.

Bạn có thể vui lòng cho tôi biết nếu có một cách dễ dàng để nhập và Excel File (tệp CSV và XLSX)?

Tôi đọc trực tuyến và tìm thấy tài liệu này nhưng tôi không chắc nó được sử dụng như thế nào trong JavaScript và HTML. Có ai giúp được không?

http://psjinx.com/programming/2014/01/04/parsing-excel-workbooks-using-javascript/


Vào ngày 9 tháng 3 năm 2020, GitHub, Inc. đã âm thầm cấm tài khoản của tôi (xóa tất cả các repos, vấn đề và nhận xét của tôi, ngay cả trong các repos riêng của chủ nhân của tôi) mà không có bất kỳ thông báo hay giải thích nào. Do đó, tất cả các mã nguồn phải được chuyển đến Gitlab ngay lập tức. Repo GitHub hiện chỉ được sử dụng làm bản sao lưu (bạn cũng có thể đóng vai chính ở đó) và repo chính hiện là Gitlab. Các vấn đề có thể được báo cáo trong bất kỳ repo.

Giấy phép

MIT

Dưới đây chúng tôi minh họa cách bạn có thể nhập bảng tính Excel vào AG Grid bằng thư viện của bên thứ ba-trong ví dụ này, chúng tôi đang sử dụng kiểu XLSX.

Trong ví dụ này, chúng tôi đang cung cấp một tệp Excel đơn giản để nhập nhưng trong ứng dụng của bạn, bạn có thể cho phép tải lên các tệp Excel của người dùng cuối.

Bảng tính chứa một vài hàng dữ liệu đơn giản, mà ví dụ phân tích cú pháp và đặt làm dữ liệu hàng.

// Loading...

npm install read-excel-file --save2

Vào ngày 9 tháng 3 năm 2020, GitHub, Inc. đã âm thầm cấm tài khoản của tôi (xóa tất cả các repos, vấn đề và nhận xét của tôi, ngay cả trong các repos riêng của chủ nhân của tôi) mà không có bất kỳ thông báo hay giải thích nào. Do đó, tất cả các mã nguồn phải được chuyển đến Gitlab ngay lập tức. Repo GitHub hiện chỉ được sử dụng làm bản sao lưu (bạn cũng có thể đóng vai chính ở đó) và repo chính hiện là Gitlab. Các vấn đề có thể được báo cáo trong bất kỳ repo.

Giấy phép

MIT

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'

// 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.
  })
})

// Blob.
fetch('https://example.com/spreadsheet.xlsx')
  .then(response => response.blob())
  .then(blob => readXlsxFile(blob))
  .then((rows) => {
    // `rows` is an array of rows
    // each row being an array of cells.
  })

// ArrayBuffer.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
//
// Could be obtained from:
// * File
// * Blob
// * Base64 string
//
readXlsxFile(arrayBuffer).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

npm install read-excel-file --save
6. 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])
})

npm install read-excel-file --save
7

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

npm install read-excel-file --save
8 khi gọi
npm install read-excel-file --save
9. 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
<input type="file" id="input" />
0 trong đó
<input type="file" id="input" />
1 sẽ là một loạt các đối tượng JSON được tạo từ dữ liệu bảng tính theo
npm install read-excel-file --save
8 và
<input type="file" id="input" />
3 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

npm install read-excel-file --save
8. 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:

  • <input type="file" id="input" />
    5 - Tên thuộc tính của đối tượng.
  • <input type="file" id="input" />
    6 - (Tùy chọn) Các thuộc tính bắt buộc có thể được đánh dấu là
    <input type="file" id="input" />
    7.
  • <input type="file" id="input" />
    8 - (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" />
    9 - (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" />
    9 đượ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" />
    9 có thể là:
    • Loại tích hợp:
      • import readXlsxFile from 'read-excel-file'
        
        // 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.
          })
        })
        
        // Blob.
        fetch('https://example.com/spreadsheet.xlsx')
          .then(response => response.blob())
          .then(blob => readXlsxFile(blob))
          .then((rows) => {
            // `rows` is an array of rows
            // each row being an array of cells.
          })
        
        // ArrayBuffer.
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
        //
        // Could be obtained from:
        // * File
        // * Blob
        // * Base64 string
        //
        readXlsxFile(arrayBuffer).then((rows) => {
          // `rows` is an array of rows
          // each row being an array of cells.
        })
        2
      • import readXlsxFile from 'read-excel-file'
        
        // 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.
          })
        })
        
        // Blob.
        fetch('https://example.com/spreadsheet.xlsx')
          .then(response => response.blob())
          .then(blob => readXlsxFile(blob))
          .then((rows) => {
            // `rows` is an array of rows
            // each row being an array of cells.
          })
        
        // ArrayBuffer.
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
        //
        // Could be obtained from:
        // * File
        // * Blob
        // * Base64 string
        //
        readXlsxFile(arrayBuffer).then((rows) => {
          // `rows` is an array of rows
          // each row being an array of cells.
        })
        3
      • import readXlsxFile from 'read-excel-file'
        
        // 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.
          })
        })
        
        // Blob.
        fetch('https://example.com/spreadsheet.xlsx')
          .then(response => response.blob())
          .then(blob => readXlsxFile(blob))
          .then((rows) => {
            // `rows` is an array of rows
            // each row being an array of cells.
          })
        
        // ArrayBuffer.
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
        //
        // Could be obtained from:
        // * File
        // * Blob
        // * Base64 string
        //
        readXlsxFile(arrayBuffer).then((rows) => {
          // `rows` is an array of rows
          // each row being an array of cells.
        })
        4
      • import readXlsxFile from 'read-excel-file'
        
        // 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.
          })
        })
        
        // Blob.
        fetch('https://example.com/spreadsheet.xlsx')
          .then(response => response.blob())
          .then(blob => readXlsxFile(blob))
          .then((rows) => {
            // `rows` is an array of rows
            // each row being an array of cells.
          })
        
        // ArrayBuffer.
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
        //
        // Could be obtained from:
        // * File
        // * Blob
        // * Base64 string
        //
        readXlsxFile(arrayBuffer).then((rows) => {
          // `rows` is an array of rows
          // each row being an array of cells.
        })
        5
    • Loại "Tiện ích" được xuất từ ​​thư viện:
      • import readXlsxFile from 'read-excel-file'
        
        // 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.
          })
        })
        
        // Blob.
        fetch('https://example.com/spreadsheet.xlsx')
          .then(response => response.blob())
          .then(blob => readXlsxFile(blob))
          .then((rows) => {
            // `rows` is an array of rows
            // each row being an array of cells.
          })
        
        // ArrayBuffer.
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
        //
        // Could be obtained from:
        // * File
        // * Blob
        // * Base64 string
        //
        readXlsxFile(arrayBuffer).then((rows) => {
          // `rows` is an array of rows
          // each row being an array of cells.
        })
        6
      • import readXlsxFile from 'read-excel-file'
        
        // 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.
          })
        })
        
        // Blob.
        fetch('https://example.com/spreadsheet.xlsx')
          .then(response => response.blob())
          .then(blob => readXlsxFile(blob))
          .then((rows) => {
            // `rows` is an array of rows
            // each row being an array of cells.
          })
        
        // ArrayBuffer.
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
        //
        // Could be obtained from:
        // * File
        // * Blob
        // * Base64 string
        //
        readXlsxFile(arrayBuffer).then((rows) => {
          // `rows` is an array of rows
          // each row being an array of cells.
        })
        7
      • import readXlsxFile from 'read-excel-file'
        
        // 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.
          })
        })
        
        // Blob.
        fetch('https://example.com/spreadsheet.xlsx')
          .then(response => response.blob())
          .then(blob => readXlsxFile(blob))
          .then((rows) => {
            // `rows` is an array of rows
            // each row being an array of cells.
          })
        
        // ArrayBuffer.
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
        //
        // Could be obtained from:
        // * File
        // * Blob
        // * Base64 string
        //
        readXlsxFile(arrayBuffer).then((rows) => {
          // `rows` is an array of rows
          // each row being an array of cells.
        })
        8
    • 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'

// 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.
  })
})

// Blob.
fetch('https://example.com/spreadsheet.xlsx')
  .then(response => response.blob())
  .then(blob => readXlsxFile(blob))
  .then((rows) => {
    // `rows` is an array of rows
    // each row being an array of cells.
  })

// ArrayBuffer.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
//
// Could be obtained from:
// * File
// * Blob
// * Base64 string
//
readXlsxFile(arrayBuffer).then((rows) => {
  // `rows` is an array of rows
  // each row being an array of cells.
})
9 (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'

// 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.
  })
})

// Blob.
fetch('https://example.com/spreadsheet.xlsx')
  .then(response => response.blob())
  .then(blob => readXlsxFile(blob))
  .then((rows) => {
    // `rows` is an array of rows
    // each row being an array of cells.
  })

// ArrayBuffer.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
//
// Could be obtained from:
// * File
// * Blob
// * Base64 string
//
readXlsxFile(arrayBuffer).then((rows) => {
  // `rows` is an array of rows
  // each row being an array of cells.
})
9 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 bằ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à ____49 để xóa nó trong quá trình hoạt động
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. Để giữ tất cả các giá trị
import readXlsxFile from 'read-excel-file'

// 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.
  })
})

// Blob.
fetch('https://example.com/spreadsheet.xlsx')
  .then(response => response.blob())
  .then(blob => readXlsxFile(blob))
  .then((rows) => {
    // `rows` is an array of rows
    // each row being an array of cells.
  })

// ArrayBuffer.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
//
// Could be obtained from:
// * File
// * Blob
// * Base64 string
//
readXlsxFile(arrayBuffer).then((rows) => {
  // `rows` is an array of rows
  // each row being an array of cells.
})
9, hãy vượt qua tùy chọn
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 khi gọi
npm install read-excel-file --save
9.

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

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

<input type="file" id="input" />
3 đượ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
<input type="file" id="input" />
3 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.
    })
    9 - Mã lỗi. 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])
    })
    0,
    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.
    • Nếu hàm
      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])
      })
      2 tùy chỉnh được xác định và nó ném
      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 thì thuộc tính
      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 sẽ giống như 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])
      })
      5.
    • Nếu hàm
      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 tùy chỉnh được xác định và nó ném
      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 thì thuộc tính
      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 sẽ giống như 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])
      })
      5.
  • 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)
      })
    }
    0 - 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" ____39s. Ví dụ:
    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)
      })
    }
    2 cho
    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 có nghĩa là "giá trị ô không hợp lệ vì nó không phải là một số".
  • 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)
      })
    }
    4 - Số hàng trong tệp gốc.
    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)
      })
    }
    5 có nghĩa là hàng đầu tiên, v.v.
  • 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 - Tiêu đề cột.
  • 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 - Giá trị ô.
  • 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 - lược đồ
    <input type="file" id="input" />
    9 cho cột này.

Một ví dụ về việc sử dụng
npm install read-excel-file --save
8

// 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" />
9 tùy chỉnh.
example.

{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}

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

// 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.

// Loading...
0

Cách sửa dữ liệu bảng tính trước khi phân tích cú pháp
npm install read-excel-file --save
8. 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

npm install read-excel-file --save
8 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
// 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 tùy chọn sẽ sửa đổi nội dung bảng tính theo yêu cầu.

// Loading...
1

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.

// Loading...
2

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.

// Loading...
3

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ư

// 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). Nếu nhà phát triển vượt qua tùy chọn
// 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 thay vì tùy chọn
npm install read-excel-file --save
8 cho
npm install read-excel-file --save
9, 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.

// Loading...
4

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ừ

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)
  })
}
5) hoặc tên trang tính trong đối số
{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}
1.

// Loading...
5

// Loading...
6

Theo mặc định,

{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}
2 là
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)
  })
}
5.

Để có được tên của tất cả các tờ, hãy sử dụng hàm

{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}
4:

// Loading...
7

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ừ

{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}
5) cùng với mô tả "định dạng" (như
{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}
6) 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

{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}
7 với tham số
npm install read-excel-file --save
8, tất cả các cột lược đồ có loại
import readXlsxFile from 'read-excel-file'

// 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.
  })
})

// Blob.
fetch('https://example.com/spreadsheet.xlsx')
  .then(response => response.blob())
  .then(blob => readXlsxFile(blob))
  .then((rows) => {
    // `rows` is an array of rows
    // each row being an array of cells.
  })

// ArrayBuffer.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer
//
// Could be obtained from:
// * File
// * Blob
// * Base64 string
//
readXlsxFile(arrayBuffer).then((rows) => {
  // `rows` is an array of rows
  // each row being an array of cells.
})
5 được phân tích điện tử tự động là ngày. Khi sử dụng
{
  'COLUMN_TITLE': {
    // This function will only be called for a non-empty cell.
    type: (value) => {
      try {
        return parseValue(value)
      } catch (error) {
        console.error(error)
        throw new Error('invalid')
      }
    }
  }
}
7 mà không có tham số
npm install read-excel-file --save
8, 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ư
// Loading...
02), người ta có thể truyền tham số
// Loading...
03 rõ ràng để hướng dẫn thư viện phân tích các ô số có "định dạng" như ngày:

// Loading...
8

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

// Loading...
04.

// Loading...
9

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

npm install read-excel-file --save
8 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
// 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 tùy chọn sẽ sửa đổi nội dung bảng tính theo yêu cầu.

// Loading...
1

Giới hạn

Màn biểu diễn

Đã có một số báo cáo về các vấn đề về hiệu suất khi đọc bảng tính

npm install read-excel-file --save
3 rất lớn bằng thư viện này. Đúng là điểm chính của thư viện này là khả năng sử dụng và thuận tiện, và không hiệu suất khi xử lý các bộ dữ liệu lớn. Ví dụ: thời gian phân tích một tệp có 2000 hàng / 20 cột là khoảng 3 giây. Vì vậy, để đọc các bộ dữ liệu khổng lồ, có lẽ sử dụng một cái gì đó như gói
// Loading...
08 thay thế. Không có điểm chuẩn so sánh giữa hai người, vì vậy nếu bạn sẽ tạo một điểm, hãy chia sẻ nó trong các vấn đề.

Công thức

Các tế bào được tính toán động bằng cách sử dụng các công thức (

// Loading...
09, v.v.) không được hỗ trợ.

TYPEXTRIPT

Tôi không phải là một chuyên gia bản thảo, vì vậy cộng đồng phải viết các kiểu đánh máy (và kiểm tra chúng). Xem ví dụ

// Loading...
10.

CDN

Người ta có thể sử dụng bất kỳ dịch vụ NPM CDN nào, ví dụ: unpkg.com hoặc jsdelivr.net

npm install read-excel-file --save
1

TYPEXTRIPT

Tôi không phải là một chuyên gia bản thảo, vì vậy cộng đồng phải viết các kiểu đánh máy (và kiểm tra chúng). Xem ví dụ

// Loading...
10.

CDN

Người ta có thể sử dụng bất kỳ dịch vụ NPM CDN nào, ví dụ: unpkg.com hoặc jsdelivr.net

Thư viện này đi kèm với "Typings" TypeScript. Nếu bạn tình cờ tìm thấy bất kỳ lỗi nào trong đó, hãy tạo ra một vấn đề.

Người giới thiệu

Sử dụng // Loading...11 để phân tích cú pháp XML.

GitHub