我试图在Django网站上生成一个excel文件,所以我搜索了它,并查看了this example。我编写了一个简单的函数,将我需要的内容写入Excel文件;
def create_excel(personal_information):
output = StringIO.StringIO()
book = xlsxwriter.Workbook(output)
sheet = book.add_worksheet()
if personal_information['name']:
sheet.write(1, 1, personal_information['name'], text_format)
book.close()
output.seek(0)
return output在我的view.py中;
def export(request):
personal_information = json.loads(request.POST.get('personal_data'))
output = create_excel(personal_information)
response = HttpResponse(output.read(), content_type="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename=Excel.xls'
return response然而,这给出了“无”。你有什么办法解决我的问题吗?
谢谢。
发布于 2018-02-07 17:08:50
试试这个:在你的函数create_excel中:
output = io.BytesIO()
workbook = xlsxwriter.Workbook(output)
.... your code .....
at the end of your function
# close workbook
workbook.close()
xlsx_data = output.getvalue()
return xlsx_data在您的视图中:
if request.method == 'POST':
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment;
filename=your_template_name.xlsx'
xlsx_data = create_excel()
response.write(xlsx_data)发布于 2020-05-20 23:43:32
我有几个解决方案。我有一个在views.py文件下执行此操作的demo project。我使用openpyxl,但如果您需要保留宏(.xlsm),也可以使用其他库,如xlwings。
下面是我的代码片段:
def export_data(request):
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="Data.xlsx"'
# create workbook
wb = Workbook()
sheet = wb.active
# stylize header row
# 'id','title', 'quantity','pub_date'
c1 = sheet.cell(row = 1, column = 1)
c1.value = "id"
c1.font = Font(bold=True)
c2 = sheet.cell(row= 1 , column = 2)
c2.value = "title"
c2.font = Font(bold=True)
c3 = sheet.cell(row= 1 , column = 3)
c3.value = "quantity"
c3.font = Font(bold=True)
c4 = sheet.cell(row= 1 , column = 4)
c4.value = "pub_date"
c4.font = Font(bold=True)
# export data to Excel
rows = models.Data.objects.all().values_list('id','category', 'quantity','pub_date',)
for row_num, row in enumerate(rows, 1):
# row is just a tuple
for col_num, value in enumerate(row):
c5 = sheet.cell(row=row_num+1, column=col_num+1)
c5.value = value
wb.save(response)
return responsehttps://stackoverflow.com/questions/35991033
复制相似问题