import React from 'react';
import * as XLSX from 'xlsx';

const ExcelImportExport = ({ members, onImport }) => {
  const handleExport = () => {
    const worksheet = XLSX.utils.json_to_sheet(members);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Members");
    XLSX.writeFile(workbook, "members.xlsx");
  };

  const handleImport = (e) => {
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onload = (event) => {
      const bstr = event.target.result;
      const workbook = XLSX.read(bstr, { type: 'binary' });
      const worksheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[worksheetName];
      const data = XLSX.utils.sheet_to_json(worksheet);
      onImport(data);
    };
    reader.readAsBinaryString(file);
  };

  return (
    <div>
      <button onClick={handleExport}>导出 Excel</button>
      <input type="file" onChange={handleImport} accept=".xlsx, .xls" />
    </div>
  );
};

export default ExcelImportExport;
