I am learner, and trying to build code to in which user has option to download the zip file that contains multiple .xlm files, which are created on the bases of database.
I have been able to create below code to download single xml file. But struggling to get multiple files packed in zipped format(for each row of database).
import xml.etree.ElementTree as ET
def export_to_xml(request):
listings = mydatabase.objects.all()
root = ET.Element('listings')
for item in listings:
price = ET.Element('price')
price.text = str(item.Name)
offer = ET.Element('offer', attrib={'id': str(item.pk)})
offer.append(price)
root.append(offer)
tree = ET.ElementTree(root)
response = HttpResponse(ET.tostring(tree.getroot()), content_type='application/xhtml+xml')
response['Content-Disposition'] = 'attachment; filename="data.xml"'
return response
Hi Got the solution by using following approach
byteStream = io.BytesIO()
with zipfile.ZipFile(byteStream, mode='w',) as zf:
# your code
zf.writestr()
response = HttpResponse(byteStream.getvalue(), content_type='application/x-zip-compressed')
response['Content-Disposition'] = "attachment; filename=finename.zip"
I am implementing csv donwloand function referring to this page.
Even though I don't get any error message, cannot get csv file downloaded.
Does anyone know what is the problem for this implementation?
Below is the code to download csv file from database.
class timeCSVexport(View):
def get(self,request,pk,keyword):
key=keyword.replace("_"," ")
queryset=timeseries.objects.filter(html__pk=pk).filter(keyword=key)
bio = BytesIO()
data=json.loads(list(queryset)[0].df)
df=pd.DataFrame.from_dict(data,orient='index').T
df.index=pd.to_datetime(df.index)
df1=df.sort_index()
sheet=key[:31] if len(key)>31 else key
print (sheet)
writer=pd.ExcelWriter(bio,engine='xlsxwriter')
df1.to_excel(writer,sheet_name=sheet)
writer.save()
bio.seek(0)
workbook=bio.getvalue()
response = StreamingHttpResponse(workbook,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s' % pk
return response
I am trying to display some csv(comma seperated values) in my project. So I have a html button click upon which a django view function is called through JavaScript. This is my django view function :
def make_csv(request):
testdata = "[{\"severity\":\"0\",\"description\":\"USB Connected\",\"date\":\"01/01/2015\",\"time\":\"11:35:20\"},{\"severity\":\"3\",\"description\":\"USB Disconnected\",\"date\":\"01/01/2015\",\"time\":\"10:30:19\"}]";
data = json.loads(testdata)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="eventlog.csv"'
writer = csv.writer(response,csv.excel)
writer.writerow(data[0].keys())
for row in data:
writer.writerow(row.values())
return response
But I can't get any file displayed in my browser. Also I can see the values returned using my JavaScript. Is there a way to display the result as a seperate file in the browser so that users can download it?
I am using pandas tool to create downloadable excel file.Excel will get it data from SQL table , which in turn will get populated depending on values entered by user.I have attached one download button in my web page to download the excel.
On clicking download button it's generating a blank excel file with sheet name and file name as Consistency Report. Can anyone point out what I am doing wrong here.
Thanks in advance
views.py
def export_excel(request):
response = HttpResponse(content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'attachment; filename=Consistency Report.xls'
fname = 'Consistency Report.xls'
cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=******;DATABASE=testing;UID=***;PWD=******')
cursor = cnxn.cursor()
cursor.execute("select * from dhm_consis_report_tbl")
columns = [column[0] for column in cursor.description]
data=cursor.fetchall()
cursor.commit()
print(columns)
for i in range(0,len(data)):
data[i]=tuple(data[i])
df = ps.DataFrame(data=data,columns=columns)
writer = ps.ExcelWriter('Consistency Report.xls',engine='xlwt')
df.to_excel(writer,sheet_name='Report')
writer.save()
return response
So, I edited my views.py and am able to generate and download excel file but the problem is that the file is now downloading at two locations; one at my project folder and one at my download folder.Also the file at download folder is empty while the one at my project folder contains data.Can anybody explain why this is happening?
Modified views.py
def export_excel(request):
response = HttpResponse(content_type="application/vnd.ms-excel;charset=utf-8")
response['Content-Disposition'] = 'attachment; filename=Consistency Report.xls'
df = ps.DataFrame.from_records(DHM_Consis_Report.objects.values('conquery_source','conquery_name','conquery_count','conquery_desc','criticality','sp_status','con_rundate','instance_id'))
print(df)
writer = ps.ExcelWriter('Consistency Report.xls',encoding='utf-8')
df.to_excel(writer,sheet_name='Report')
writer.save()
return response
Finally, I was able to generate required excel.Earlier I was creating and writing the excel with data but my HttpResponse was not getting the required data.I put the logic regarding generating excel in separate function and logic regarding downloading the generated file in separate function.This is what I did.
I know it's crude and inefficient but this works for me.If anyone has better way to do this please share.
views.py
#login_required
def consisreports(request):
cust= customername
username=None
if request.user.is_authenticated():
username=request.user.username
print(username)
table=ConsisReport(DHM_Consis_Report.objects.all())
RequestConfig(request,paginate={"per_page": 25}).configure(table)
todays=date.today()
todays=todays.strftime("%d-%m-%y")
filename="Consistency Report %s as on %s %s.xls"%(cust,str(todays),username)
colname=['Customer','Query ','Count','Desc','Criticality','Status','Rundate','Instance ID']
df = ps.DataFrame.from_records(DHM_Consis_Report.objects.values('conquery_source','conquery_name','conquery_count','conquery_desc','criticality','sp_status','con_rundate','instance_id'))
df=df[['conquery_source','conquery_name','conquery_count','conquery_desc','criticality','sp_status','con_rundate','instance_id']]
print(df)
#df.save('C:/Users/P1097/Desktop')
writer = ps.ExcelWriter(filename)
df.to_excel(writer,sheet_name='Report',index=False,engine='xlsxwriter',header=colname)
writer.save()
return render(request, 'consistency/consresult.html', {'table': table,'customername':cust})
#login_required
def export_excel(request):
custname=customername
username=None
if request.user.is_authenticated():
username=request.user.username
todays=date.today()
todays=todays.strftime("%d-%m-%y")
filename="Consistency Report %s as on %s %s.xls"%(custname,str(todays),username)
wrapper=open(filename,"rb")
cont=wrapper.read()
response = HttpResponse(cont,content_type="application/vnd.ms-excel;charset=utf-8")
response['Content-Length']=os.path.getsize(filename)
size=os.path.getsize(filename)
print(size)
wrapper.close()
response['Content-Disposition'] = 'attachment; filename= %s'%filename
return response
I have a django model as follows:
class ExportFile(BaseExportFile):
created_timestamp = models.DateTimeField(auto_now=True, editable=False)
data = models.FileField(upload_to='exports')
and a view function that renders a template to create a csv file:
def create_csv(request):
context = Context({'data': MyModel.objects.all()})
rendered = render_to_string('mytemplate.html', context)
# create tradefile and save
cf = ContentFile(rendered)
tf = ExportFile()
tf.data.save('myfile.csv', cf)
tf.save()
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % 'myfile.csv'
response.write(rendered)
return response
The view not only saves the csv data to a FileField but it also returns it to the browser. The problem I have is the browser file works perfectly, but the file saved on the model is twice the size and when I use a diff program I can see extra hidden characters. I think it must be to do with the mime type vs django auto saving utf8 but I just can't figure it out!
Solved the problem!
The ContentFile is a subclass of cStringIO.StringIO - which deals with ASCII encoded files. The string therefore needs to be encoded as ASCII as everything in django is UTF8 by default
cf = ContentFile(rendered.encode('ascii'))