Django返回EXcel
coding:utf-8
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse
from app.models import *
from app.form import LoginForm
from django.http import JsonResponse
import json
from json import loads, dumps
import simplejson
from django.views.decorators.csrf import csrf_exempt
import json
from django.contrib.auth.decorators import permission_required
from app.views import *
import xlwt
import StringIO
from django.http import HttpResponse
from app.models import Sensor, SensorData
import json
from django.core.serializers.json import DjangoJSONEncoder
def excel_ajax(request):
if request.method == 'GET':
d1 = request.GET.get('data1')
d2 = request.GET.get('data2')
d3 = request.GET.get('data3')
d4 = request.GET.get('data4')
d5 = request.GET.get('data5')
d6 = request.GET.get('data6')
d7 = request.GET.get('data7')
d8 = request.GET.get('data8')
data_start = request.GET.get('data_start')
data_end = request.GET.get('data_end')
response = HttpResponse()
response['Content-Disposition'] = 'attachment;filename=excel.xls'
wb = xlwt.Workbook(encoding='utf-8')
sheet = wb.add_sheet(u'订单')
my_time = []
guang = []
co=[]
PH=[]
temp=[]
for i in SensorData.objects.filter(collertor_id=2):
co.extend([i.sensor_CO2])
guang.extend([i.sensor_guang])
PH.extend([i.sensor_tu_PH])
temp.extend([i.sensor_temp])
# 1st line
sheet.write(0, 0, '光照')
sheet.write(0, 1, 'PH')
sheet.write(0, 2, '温度')
sheet.write(0, 3, '湿度')
List = []
row = 1
for i in guang:
sheet.write(row, 0, i) # 此处是在第一列添加数据
# sheet.write(row,1, '测试1')#此处在第二列添加数据
# sheet.write(row,2,'测试2')#此处在第二列添加数据
# sheet.write(row,3,'测试3')#此处在第二列添加数据
row = row + 1
row=1
for i in PH:
sheet.write(row,1, i)#此处在第二列添加数据
row=row+1
row =1
for i in co:
sheet.write(row,2, i)#此处在第二列添加数据
row=row+1
row=1
for i in temp:
sheet.write(row,3, i)#此处在第二列添加数据
row=row+1
output = StringIO.StringIO()
wb.save(output)
output.seek(0)
response.write(output.getvalue())
return response
#return HttpResponse(data_start);
def farm_ajax(request):
if request.method == 'GET':
d1 = request.GET.get('data1')
d2 = request.GET.get('data2')
d3 = request.GET.get('data3')
d4 = request.GET.get('data4')
d5 = request.GET.get('data5')
d6 = request.GET.get('data6')
d7 = request.GET.get('data7')
d8 = request.GET.get('data8')
data_start = request.GET.get('data_start')
data_end = request.GET.get('data_end')
result =excel_ajax(request)
return HttpResponse(result)