首页 > 解决方案 > 使用 Pandas 在 Python CGI 脚本中读取上传的 XLSX 文件

问题描述

我正在创建一个工具

  1. 生成一个新的 XLSX 文件供用户下载
  2. 用户可以上传他们拥有的 XLSX 文件,我将读取该文件的内容,并使用它们生成一个新文件供用户下载。

我想利用 Pandas 将 XLSX 文件读入数据框,这样我就可以轻松使用它。但是,我无法让它工作。你能帮助我吗?

从 CGI 文件中提取的示例:

import pandas as pd
import cgi
from mako.template import Template
from mako.lookup import TemplateLookup
import http.cookies as Cookie
import os
import tempfile
import shutil
import sys

cookie = Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))

method = os.environ.get("REQUEST_METHOD", "GET")

templates = TemplateLookup(directories = ['templates'], output_encoding='utf-8')

if method == "GET": # This is for getting the page
    
    template = templates.get_template("my.html")
    sys.stdout.flush()
    sys.stdout.buffer.write(b"Content-Type: text/html\n\n")
    sys.stdout.buffer.write(
        template.render())

if method == "POST":

    form = cgi.FieldStorage()
    print("Content-Type: application/vnd.ms-excel")
    print("Content-Disposition: attachment; filename=NewFile.xlsx\n")
    
    output_path = "/tmp/" + next(tempfile._get_candidate_names()) + '.xlsx'
    
    data = *some pandas dataframe previously created*

    if "editfile" in form:
        myfilename = form['myfile'].filename
        with open(myfilename, 'wb') as f:
            f.write(form['myfile'].file.read())                
        data = pd.read_excel(myfilename)

    data.to_excel(output_path)

    with open(path, "rb") as f:
        sys.stdout.flush()
        shutil.copyfileobj(f, sys.stdout.buffer)

从 HTML 文件中提取的示例:

<p>Press the button below to generate a new version of the xlsx file</p> 
<form method=post>
<p><input type=submit value='Generate new version of file' name='newfile'>
<div class="wrapper">
</div>
</form>
<br>
<p>Or upload a file.</p>
<p>In this case, a new file will be created using the contents of this file.</p>
<form method="post" enctype="multipart/form-data">
    <input id="fileupload" name="myfile" type="file" />
    <input value="Upload and create new file" name='editfile' type="submit" />
</form>

if "editfile" in form:一点也没有问题,所以当我尝试访问用户上传的文件时,我知道出了点问题。

问题是在创建文件时,创建的文件的文件大小为 0 KB,不会在 Excel 中打开。至关重要的是,在我写出的位置找不到用户上传的文件。

标签: pythonpandascgi

解决方案


你已经传给myfilename了熊猫;但是该文件在服务器上尚不存在。在使用之前,您必须先将文件保存在本地某处。

以下将文件下载到当前目录(与 CGI 脚本相同的目录)。当然,欢迎您将其保存到更合适的目录中,具体取决于您的设置。

form = cgi.FieldStorage()
myfilename = form['myfile'].filename
with open(myfilename, 'wb') as f:  # Save the file locally
    f.write(form['myfile'].file.read())
data = pd.read_excel(myfilename)

推荐阅读