import io
from django.http import HttpResponse
from django.views.generic import View
import xlsxwriter
def get_simple_table_data():
# Simulate a more complex table read.
return [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
class MyView(View):
def get(self, request):
# Create an in-memory output file for the new workbook.
output = io.BytesIO()
# Even though the final file will be in memory the module uses temp
# files during assembly for efficiency. To avoid this on servers that
# don't allow temp files, for example the Google APP Engine, set the
# 'in_memory' Workbook() constructor option as shown in the docs.
workbook = xlsxwriter.Workbook(output)
worksheet = workbook.add_worksheet()
# Get some data to write to the spreadsheet.
data = get_simple_table_data()
# Write some test data.
for row_num, columns in enumerate(data):
for col_num, cell_data in enumerate(columns):
worksheet.write(row_num, col_num, cell_data)
# Close the workbook before sending the data.
workbook.close()
# Rewind the buffer.
output.seek(0)
# Set up the Http response.
filename = 'django_simple.xlsx'
response = HttpResponse(
output,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
6条答案
按热度按时间kyxcudwk1#
对Python 3的@alecxe响应(io. BytesIO而不是StringIO. StringIO)和Django〉= 1.5(content_type而不是mimetype)进行了一点更新,使用了完全在内存中的文件汇编,该文件汇编已经由@jmcnamara实现({' in_memory ':正确})!
下面是完整的示例:
jslywgbw2#
我想你问的是如何使用
xlsxwriter
在内存中创建一个excel文件,并通过HttpResponse
返回它。gmol16393#
说到Django,你甚至可以不使用
StringIO
的所有诡计。HttpResponse
在这方面的行为就像StringIO:补充:您需要指定
{'in_memory': True}
,否则可能会得到HttpResponse has no attribute seek()
。jhkqcmku4#
最好遵循jmcnamara(软件包开发商)的官方文档
Example: Simple Django class
7lrncoxx5#
我在
reportProgress: True
中使用nodejs,我的Django代码是这样的;如果你这样做,你就可以像这样
mefy6pfw6#
使用XlsxWriter模块编写Excel文件的简单Django View类。