简体   繁体   English

如何生成 excel 文件并将其作为文件保存到数据库

[英]How to generate an excel file and save it to database as a file

I have created a function that creates an excel file using xlwt.我创建了一个 function,它使用 xlwt 创建了一个 excel 文件。 I was able to download it as file but I want it to be saved to the database first and what I did does not work.我能够将其作为文件下载,但我希望先将其保存到数据库中,而我所做的却不起作用。

Here's what I did so far.这是我到目前为止所做的。

import xlwt

response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="excel-file.xls"'

wb = xlwt.Worbook()
# some excel file generating code here
wb.save(response)

return response

After generating the excel file, I tried it to save it to the database but doing this does not work.生成 excel 文件后,我尝试将其保存到数据库中,但这样做不起作用。 (Code below) (代码如下)

# file = models.FileField
Reports.objects.create(
   file=wb
)

I have also tried saving it to a stream first but saving it like this also does not work.我也尝试过先将其保存到 stream 但这样保存也不起作用。 (Code below) (代码如下)

f = io.StringIO()
wb.save(f)

# file = models.FileField
Reports.objects.create(
   file=f
)

OK, I think I understand what you are asking now.好的,我想我明白你现在在问什么了。

Unfortunately, the FileField class is designed to save an (uploaded) file in the file system, not the database.不幸的是, FileField class 旨在将(上传的)文件保存在文件系统中,而不是数据库中。 This is probably a good thing.这大概是件好事。 Databases are not designed to be used as file systems.数据库并非旨在用作文件系统。 But either way, if you use FileField the database will only contain the file name, not the file content.但无论哪种方式,如果您使用FileField数据库将只包含文件名,而不包含文件内容。

So my first suggestion is to use FileField and FileSystemStorage as intended.所以我的第一个建议是按预期使用FileFieldFileSystemStorage There is some example code in https://docs.djangoproject.com/en/3.0/topics/files/#file-storage that shows how to save some stuff into the default file storage. https://docs.djangoproject.com/en/3.0/topics/files/#file-storage中有一些示例代码显示了如何将一些内容保存到默认文件存储中。

Alternatively, if you really want to store your Excel object in the database, then you need to change the FileField to a BinaryField .或者,如果您真的想将 Excel object 存储在数据库中,则需要将FileField更改为BinaryField Then you can do something like this:然后你可以做这样的事情:

  buffer = BytesIO()
  wb.save(buffer)
  // excel = models.BinaryField()
  Reports.object.create(excel=buffer.getValue(), ...)

(There are probably more efficient ways to do this.) (可能有更有效的方法来做到这一点。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM