You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目使用@rpldy/uploady上传Excel/CSV后如何展示文件内容

实现方案

1. 安装依赖

首先补充安装Excel、CSV格式解析库:

npm install xlsx papaparse

2. 完整实现代码

import Uploady, { useItemFinishListener } from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";
import { useState } from "react";
import * as XLSX from 'xlsx';
import Papa from 'papaparse';

// 上传逻辑处理组件
const UploadContentHandler = () => {
  // 用state暂存解析后的文件内容,存在组件内存中即可满足需求
  const [fileContent, setFileContent] = useState('');

  // 监听文件上传完成事件
  useItemFinishListener((item) => {
    const file = item.file;
    const reader = new FileReader();

    reader.onload = (e) => {
      const fileData = e.target.result;
      // 解析CSV格式
      if (file.name.endsWith('.csv')) {
        Papa.parse(file, {
          encoding: 'utf-8',
          complete: (parseRes) => {
            const content = parseRes.data.map(row => row.join(',')).join('\n');
            setFileContent(content);
          }
        })
      }
      // 解析Excel格式
      else if (file.name.match(/\.(xls|xlsx)$/)) {
        const workbook = XLSX.read(fileData, { type: 'binary' });
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const content = XLSX.utils.sheet_to_csv(firstSheet);
        setFileContent(content);
      }
    };

    if (file.name.match(/\.(xls|xlsx)$/)) {
      reader.readAsBinaryString(file);
    } else {
      reader.readAsText(file);
    }
  });

  return (
    <>
      <UploadButton/>
      {/* 渲染解析后的内容 */}
      {fileContent && (
        <div style={{ marginTop: 20, whiteSpace: 'pre-wrap', border: '1px solid #e5e7eb', padding: 12, borderRadius: 4 }}>
          <h4>文件内容</h4>
          {fileContent}
        </div>
      )}
    </>
  )
}

export function Page() {
  return (
    <div>
      <main>
        <Uploady destination={{ url: "https://my-server/upload" }}>
          <UploadContentHandler />
        </Uploady>
      </main>
    </div>
  );
}

逻辑说明

  • 暂存方案直接使用React内置的useState即可,解析后的内容存在组件内存中,页面不刷新就不会丢失,完全满足普通展示需求
  • 上传完成的回调通过@rpldy/uploady提供的useItemFinishListener钩子实现,可直接拿到上传的源文件对象
  • 不同格式的文件分别调用对应的解析库处理,统一转成文本字符串存入状态后渲染

可选优化

如果不需要等待上传到服务器完成再展示内容,可以把useItemFinishListener替换为useItemStartListener,用户选择文件后立刻解析展示,无需等待接口返回,体验更流畅。


内容的提问来源于stack exchange,提问作者user13067694

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 15:15:05