react如何导出excel

5 阅读1分钟

1. 下载依赖

yarn add xlsx file-saver

文档:

2. 使用示例

import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';

const list = [
  { id: '000001', name: '张三' },
  { id: '000002', name: '李四' } 
]

const exportToExcel = () => {
  // 导出的数据组装
  const data = list.map((item, index) => ({
    No: index + 1,
    id: item.id,
    name: item.name
  }))
  
  // 创建一个sheet
  const worksheet = XLSX.utils.json_to_sheet(data); 
  // 新建excel实例
  const workbook = XLSX.utils.book_new(); 
  // 新建的excel实例添加创建的sheet
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1"); 

  // 生成导出对象
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
  saveAs(dataBlob, "导出名字" + '.xlsx'); // 导出名字 - 可自定义
};

3. 如何与系统使用的多语言进行匹配

这里以 react, react-i18next 为示例

import { FC } from "react";
import { useTranslation } from "react-i18next";
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';

const OrderList: FC = () => {

  const { t } = useTranslation();

  const list = [
    { number: '000001', name: '张三', age: 10 },
    { number: '000002', name: '李四', age: 20 },
  ]

  const exportToExcel = () => {
  // 导出的数据组装
  const data = list.map((item, index) => ({
    [t("number")]: item?.number ?? '', // t("number") 是多语言用法
    [t("name")]: item?.name ?? '', 
    [t("age")]: item?.age ?? '', 
  }))
  
  // 创建一个sheet
  const worksheet = XLSX.utils.json_to_sheet(data); 
  // 新建excel实例
  const workbook = XLSX.utils.book_new(); 
  // 新建的excel实例添加创建的sheet
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1"); 

  // 生成导出对象
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
  saveAs(dataBlob, "导出名字" + '.xlsx'); // 导出名字 - 可自定义
};
  
  return <button onClick={exportToExcel}>导出Excel</button>
}