首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django上传excel文件,处理与熊猫,下载为csv

Django上传excel文件,处理与熊猫,下载为csv
EN

Stack Overflow用户
提问于 2018-07-20 15:45:13
回答 1查看 5K关注 0票数 1

我在本地主机上运行Django (稍后在LAN上运行),其中的想法是我可以进入网页,单击提示您从计算机中选择excel文件的按钮。熊猫将处理上述excel文件,Django/Pandas将制作此Pandas数据框架的excel文件作为下载提示。

我已经让Django运行并使用了模块'Django-Excel‘中的代码来完成我想要的基本功能。Excel文件在-> excel文件中,没有将文件保存到数据库或任何仅保存在内存中的东西。然而,我却找不到办法把潘达斯塞进里面。我面临的主要问题是我不确定如何使用Pandas返回excel文件。但是,我一直在我的脱机python代码中使用'.to_excel()‘,但是没有找到在运行Django的本地主机中使用它的方法。我肯定我错过了一些很简单的东西,但我就是搞不懂。

也许有人可以举一个简单的例子,比如上传一个excel,熊猫会将excel中的一列数字乘以2,然后输出新的excel来读取/保存。

代码语言:javascript
复制
from django.shortcuts import render, redirect
from django.http import HttpResponseBadRequest, HttpResponse
from _compact import JsonResponse
from django import forms
import django_excel as excel
from polls.models import Question, Choice


class UploadFileForm(forms.Form):
file = forms.FileField()


# Create your views here.
def upload(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            filehandle = request.FILES['file']
            # do pandas here to filehandle/ put filehandle into a function 
            return excel.make_response(filehandle.get_sheet(), "csv",
                                       file_name="download")
    else:
        form = UploadFileForm()
    return render(
        request,
        'upload_form.html',
        {
            'form': form,
            'title': 'Excel file upload and download example',
            'header': ('Please choose any excel file ' +
                       'from your cloned repository:')
})

非常感谢,如果这不是很清楚,这是我第一次在这个网站上发布,如果你不明白我要求什么,我会详细说明。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-23 14:12:15

我会上传我的答案,供任何人在未来看到这个:-)

代码语言:javascript
复制
def uploads(request):
    if request.method == "POST":
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            kappa = request.FILES['file']
            # Do work on kappa/excel file here with Pandas
            output = io.BytesIO()
            writer = pd.ExcelWriter(output, engine='xlsxwriter')
            kappa.to_excel(writer, index=False)
            writer.save()
            output.seek(0)
            response = HttpResponse(output,
                                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % 'Download'
        return response
else:
    form = UploadFileForm()
return render(request, 'upload_form.html', {'form': form})

我放弃了使用'Django-excel‘,而是使用了io模块中的'BytesIO’。这有一个好处就是不依赖第三方模块。您可以将Pandas编写到io.BytesIO(),然后在您的HttpResponse中使用它。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51446156

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档