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

如何使用<py-script>读取本地目录中的Excel文件?

如何用读取本地Excel文件?

问题详情

  • 需求:用<py-script>读取本地目录里的Excel文件
  • 问题:<py-script>基于Pyodide运行,默认工作目录是/home/pyodide,无法直接访问本地文件,尝试读取时会抛出:FileNotFoundError: [Errno 44] No such file or directory

测试代码:

<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
  </head>
  <body>
    <py-script>
      import os

      print(os.listdir())
      print(os.getcwd())
    </py-script>
  </body>
</html>

可行方案

浏览器的沙盒安全机制禁止网页直接读取本地文件,所以必须通过用户主动上传文件的方式实现,具体步骤如下:

实现代码

<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    <py-config>
      <!-- 声明需要的Python包 -->
      packages = ["pandas", "openpyxl"]
    </py-config>
  </head>
  <body>
    <!-- 文件上传控件,限制仅接受Excel格式 -->
    <input type="file" id="excel-upload" accept=".xlsx, .xls">
    <!-- 用于显示解析结果的容器 -->
    <div id="output"></div>

    <py-script>
      from pyodide.ffi import create_proxy
      import pandas as pd
      from io import BytesIO
      from js import document

      def handle_upload(event):
        # 获取用户上传的文件
        file = event.target.files[0]
        # 创建FileReader读取文件内容
        reader = js.FileReader.new()
        # 绑定文件读取完成后的处理函数
        reader.onload = create_proxy(process_excel_file)
        # 以ArrayBuffer格式读取文件
        reader.readAsArrayBuffer(file)

      def process_excel_file(event):
        # 将浏览器的ArrayBuffer转为Python可处理的BytesIO
        buffer = event.target.result
        excel_data = BytesIO(bytes(buffer))
        
        # 用pandas解析Excel文件
        df = pd.read_excel(excel_data, engine="openpyxl")
        # 将解析结果转为HTML并显示在页面上
        output_area = document.getElementById("output")
        output_area.innerHTML = df.to_html(index=False)

      # 给上传控件绑定change事件
      upload_input = document.getElementById("excel-upload")
      upload_input.addEventListener("change", create_proxy(handle_upload))
    </py-script>
  </body>
</html>

核心要点

  • 必须依赖用户主动选择上传文件,这是浏览器安全规则,无法绕过
  • 通过pyodide.ffi.create_proxy实现Python与JavaScript的事件交互
  • 需要在<py-config>里声明依赖的Python包(比如解析Excel需要的pandas和openpyxl)
  • 读取文件时要把浏览器返回的ArrayBuffer转换成Python的BytesIO对象,才能被pandas识别

内容的提问来源于stack exchange,提问作者Rohít Jíndal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:13:33