python内存中生成excel和zip文件

python内存中生成excel和zip文件

我们知道pandas和zipfile两个库可以生成Excel文件和Zip文件,但是正常情况下会直接在服务器上生成文件,如果这些文件是一次性的或者不常用,那么就会造成资源的浪费,所以最好的方法是不在服务器生成文件,直接把该文件对象返回。

原理其实是使用BytesIO在内存中生成类文件对象,然后通过FileResponse返回, 这样就不会在本地服务器上生成该文件

BytesIO是需要.close的,但是由于FileResponse会自动关闭,所以这里不需要手动关闭

直接返回Zip文件

import zipfile
from django.http.response import FileResponse
from io import BytesIO


class TestZip(APIView):
    def get(self, request, *args, **kwargs):
        to_zip = BytesIO()
        with zipfile.ZipFile(to_zip, "w") as f:
            f.write("/Users/zonghan/Desktop/xxx.md", arcname="xxx.md")  # arcname参数为解压后的文件名,不指定的话和第一个参数一样,但是这样解压后会生成/Users/zonghan/Desktop/路径,直接指定的话解压后就为xxx.md文件
        to_zip.seek(0)  # 很重要,必须要把指针置为0,否则文件无效
        return FileResponse(
            to_zip, filename="test.zip", as_attachment=True
        )

image

直接返回Excel文件

import pandas as pd
from django.http.response import FileResponse
from io import BytesIO


class TestExcel(APIView):
    def get(self, request, *args, **kwargs):
        df = pd.DataFrame({"ID": [1, 2, 3], "NAME": ["Nick", "Bob", "Tom"]})
        to_write = BytesIO()
        df.to_excel(to_write, index=False)
        to_write.seek(0)  # 很重要,必须要把指针置为0,否则文件无效
        return FileResponse(
            to_write, filename="test.xlsx", as_attachment=True
        )

image

内存中生成Excel文件再压缩生Zip文件

import zipfile
import pandas as pd
from django.http.response import FileResponse
from io import BytesIO


class TestExcelAndZip(APIView):
    def get(self, request, *args, **kwargs):
        df = pd.DataFrame({"ID": [1, 2, 3], "NAME": ["Nick", "Bob", "Tom"]})
        to_write = BytesIO()
        df.to_excel(to_write, index=False)
        to_write.seek(0)
        with BytesIO() as to_write:
            df.to_excel(to_write, index=False)
            to_write.seek(0)
            excel_data = to_write.getvalue()  # 这里把二进制数据赋值给excel_data变量后BytesIO对象就关闭来

        to_zip = BytesIO()
        with zipfile.ZipFile(to_zip, "w") as f:
            f.writestr("xxx.xlsx", data=excel_data)
            # writestr方法是在压缩文件内生成一个文件,文件内容为data接收的参数
        to_zip.seek(0)
        return FileResponse(
            to_zip, filename="test.zip", as_attachment=True
        )

这样就在内存中生成了excel文件和zip文件,并没有在硬盘上生成文件,然后直接把文件返回,客户端获得文件

posted @ 2023-01-17 16:38  zong涵  阅读(225)  评论(0编辑  收藏  举报