Phản ứng xuất mã excel-excelandbox

Có một số điều kiện quyết định đầu tiên cho hướng dẫn này. Bạn cần tạo một dự án React với ứng dụng tạo-ứng dụng phản ứng và cần cài đặt các gói npm xslx, bootstrapand file-saver

// generate react project
create-react-app react-exportexcel-example
// install bootstrap
npm install react-bootstrap bootstrap --save
// install xsls and file-saver
npm install xlsx file-saver --save

You have to add stylesheets from the library React Bootstrap in

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <!-- Bootstrap stylesheet link -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
2

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <!-- Bootstrap stylesheet link -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

Tạo tiêu đề cho Header

import React from 'react'

export const Header = () => {
    return (
        <div className="header">
            <h1>React Export To Excel Example</h1>
        </div>
    )
}

Tạo bảng khách hàng

Please create a component table Khách hàng. Đây là một trình bày thành phần trong đó đưa ra các khách hàng làm props và renders làm bảng

import React from 'react'
import Table from 'react-bootstrap/Table';

export const Customers = ({customers}) => {

    const CustomerRow = (customer,index) => {

        return(
              <tr key = {index} className='even'>
                  <td> {index + 1} </td>
                  <td>{customer.firstName}</td>
                  <td>{customer.lastName}</td>
                  <td>{customer.email}</td>
                  <td>{customer.address}</td>
                  <td>{customer.zipcode}</td>
              </tr>
          )
      }

      const CustomerTable = customers.map((cust,index) => CustomerRow(cust,index))

      const tableHeader = <thead className='bgvi'>
                            <tr>
                                <th>#</th>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Email</th>
                                <th>Address</th>
                                <th>Zipcode</th>
                            </tr>
                        </thead>
    
    return (
        <Table striped bordered hover>
            {tableHeader}
            <tbody>
                {CustomerTable}
            </tbody>
        </Table>
    )
}

Truyền dữ liệu từ thành phần Ứng dụng

Chúng ta nên chuyển dữ liệu được hiển thị trong bảng từ thành phần Ứng dụng như bên dưới và chúng ta cũng cần nhập thành phần Khách hàng và Tiêu đề để sử dụng các dữ liệu trong chức năng kết xuất

import React from 'react';
import './App.css';
import { Customers } from './Customers'
import { Header } from './Header'

class App extends React.Component {

  customers = () => {
    let custs = []
    for (let i = 0; i <= 25; i++) {
      custs.push({firstName: `first${i}`, lastName: `last${i}`,
      email: `abc${i}@gmail.com`, address: `000${i} street city, ST`, zipcode: `0000${i}`});
    }
    return custs;
  }
  
  render() {

    return (
      <div className="App">
        <Header />
        <Customers customers={this.customers()}/>
      </div>
    );
  }
}

export default App;

Ứng dụng của bạn sẽ giống như thế này.

3. Thực hiện các chức năng xuất khẩu

Please create a component has name is ExportCSV which get data doing props and quan tâm đến phần còn lại của chức năng export. Đây là thành phần với phương thức exportToCSV để xử lý tất cả các chức năng tải xuống excel với xlxs và trình tiết kiệm tệp

import React from 'react'
import Button from 'react-bootstrap/Button';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

export const ExportCSV = ({csvData, fileName}) => {

    const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
    const fileExtension = '.xlsx';

    const exportToCSV = (csvData, fileName) => {
        const ws = XLSX.utils.json_to_sheet(csvData);
        const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
        const data = new Blob([excelBuffer], {type: fileType});
        FileSaver.saveAs(data, fileName + fileExtension);
    }

    return (
        <Button variant="warning" onClick={(e) => exportToCSV(csvData,fileName)}>Export</Button>
    )
}

Thành phần này là một thành phần trình bày lấy dữ liệu để tải xuống và tên tệp làm đạo cụ. Phương thức exportToCSV được gọi khi nhấp vào nút xuất

You must enter this component in App component

// removed for brevity
render() {

    return (
      <div className="App">
        <Header />
        <div className="row">
            <div className="col-md-8">
                <h2>Customers</h2>
            </div>
            <div className="col-md-4 center">
                <ExportCSV csvData={this.state.customers} fileName={this.state.fileName} />
            </div>
        </div>
        <Customers customers={this.customers()}/>
      </div>
    );
  }

Màn hình sau đây là màn hình cuối cùng sau khi chúng tôi bổ sung tất cả các chức năng trên và sẵn sàng hoạt động.

4. Chức năng Xuất khẩu với phụ kiện NPM lib

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <!-- Bootstrap stylesheet link -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
3 là thư viện bên thứ ba mà chúng ta có thể sử dụng. Tất cả công việc chúng ta cần làm là truyền dữ liệu và tên tệp và thư viện này sẽ mất phần còn lại cho chúng ta

Chúng ta cần cài đặt

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <!-- Bootstrap stylesheet link -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
3 trước và sau đó nhập nó vào thành phần ExportCSV

npm install react-csv --save

Nhập CSVLink từ Reac-csv và chuyển dữ liệu cần thiết và đặt tên tệp vào liên kết đó như bên dưới

import React from 'react'
import { CSVLink } from 'react-csv'
import Button from 'react-bootstrap/Button';

export const ExportReactCSV = ({csvData, fileName}) => {
    return (
        <Button variant="warning">
            <CSVLink data={csvData} filename={fileName}>Export</CSVLink>
        </Button>
    )
}

Trong thành phần Ứng dụng, tất cả những gì bạn cần làm là nhập vào

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <!-- Bootstrap stylesheet link -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
5 thay vì
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <!-- Bootstrap stylesheet link -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
6

// generate react project
create-react-app react-exportexcel-example
// install bootstrap
npm install react-bootstrap bootstrap --save
// install xsls and file-saver
npm install xlsx file-saver --save
05. Tóm tắt
  • Chúng ta cần xlsx và libs của trình bảo vệ tệp để thực hiện chức năng xuất trong React
  • Có một số cách bạn có thể phát triển logic export của mình trong React. một là sử dụng logic riêng, một cách khác là sử dụng bất kỳ lib bên thứ ba nào
  • Thực hiện xuất logic với thành phần riêng biệt để có thể sử dụng lại và cũng có thể được nhập vào bất kỳ thành phần nào để sử dụng nó
6. Phần kết luận

Có một số lib bên thứ ba hoặc npm để sử dụng ngay. Nhưng đôi khi chúng ta phải tạo thành phần riêng cho chức năng xuất để có thể hoạt động linh hoạt hơn và các mục đích khác như lý do bảo mật. Cảm ơn các bạn đã theo dõi. Trong bài viết có tham khảo tại https. //Blog. bitrc. io/xuất-dữ-liệu-to-excel-with-Reac-6943d7775a92