Not able to see converted Excel to HTML through Django - python

I have converted on Excel(with 2 tabs) to HTML. Now I want to display this generated HTML on a webpage with Django code. But I am not able to get the entire data in my webpage.
Following is my Django code.
#api_view(['GET'])
def download_y9cfile1(request, file_name):
filePath = CommonUtils.get_absolute_file_path('app','static','generated','HTML', file_name)
logger.debug("File name is %s" % filePath )
try:
relevantFile = open(filePath,'rb')
response = HttpResponse((relevantFile), content_type='text/html')
response['Content-Disposition'] = 'inline; filename="%s"' %file_name
except IOError:
logger.exception("File doesn't exist")
return HttpResponse("File doesn't exist", status=500)
return response
I think the issue is that Django is not able to read the supporting CSS file for HTML.

Try passing the file contents to HttpResponse instead of the file handle:
response = HttpResponse(relevantFile.read(), content_type='text/html')

Related

Django: How do I download .xls file through a django view

I have a button which downloads a excel file with extension .xls. I am using module xlrd to parse the file and return it back to the user. However it appears to add the object name into the excel file instead of the data.
How can I return the file to the user with the data rather than the objects name?
View
def download_file(self, testname):
import csv, socket, os, xlrd
extension = '.xls'
path = r"C:\tests\{}_Report{}".format(testname, extension)
try:
f = xlrd.open_workbook(path)
response = HttpResponse(f, content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension)
return response
except Exception as Error:
return HttpResponse(Error)
return redirect('emissions_dashboard:overview_view_record')
Excel result
Download successful:
Content:
Note: I understand this is an old file format but is required for this particular project.
You are trying to send a xlrd.book.Book object, not a file.
You used xlrd to do your things in the workbook, and then saved to a file.
workbook = xlrd.open_workbook(path)
#... do something
workbook.save(path)
Now you send it like any other file:
with open(path, 'rb') as f:
response = HttpResponse(f.read(), content_type="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension)

Return dynamically generated zip file as json response when download button is clicked

I am dynamically generating zip file with result after user searches for data. I want to return the zip file as a json response and allow user to download it when download button is clicked.
Below is the code i have used which returns HttpResponse. I want to convert this to a json response. I tried a few approaches and it didn't work. I am not sure how the url should be specified in the template and also the url pattern for the same.
Below is the code I have used in the view:
filename = "{}_{}.txt".format(query_word, doc_id)
zip_dir = "result_for_query_{}.zip".format(query_word)
z = zipfile.ZipFile(zip_dir, 'a')
self.write_to_file(filename, doc, z)
z.close()
response = HttpResponse(z,content_type='application/zip')
response["Content-Disposition"] = "attachment; filename=%s" % zip_dir
return response
And my template:
Download
I am new to programming. So, I am still learning how to write urlpatterns.

docx file downloaded from Django is corrupt

Im trying to take user input from a form and then using that data to create a document using python docx module. But the downloaded file is not opening in MS word. It says the file is corrupt. Can someone help me with this?
def resume_form(request):
form = forms.resume()
if request.method == 'POST':
form = forms.resume(request.POST)
if form.is_valid():
document = Document()
document.add_heading(str(form.cleaned_data['full_name']),0)
document.add_heading('Summary', 1)
document.add_paragraph(str(form.cleaned_data['summary']))
f = io.BytesIO()
document.save(f)
length = f.tell()
f.seek(0)
response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename=download.docx'
response['Content-Length'] = length
#document.save(response)
return response
return render(request, 'sample_app/index.html', {'form' : form})
I think you have the answer already in your code: you can (and should) write your document directly to the response, rather than use an intermediary BytesIO.
...
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename = "download.docx"'
document.save(response)
return response
You must read from io in the response with getvalue(), since you're writing document to io.
response = HttpResponse(f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
Or you can write directly to response as #paleolimbot pointed out.

Downloading file from FileField in Django with a HTTP link in a HTML file

I create a link that when a user press it, it will download a pdf file from the media folder in Django to the users machine.
I tried different methods but all were wrong for me. It tells me that the file can not be found, or the code is running but the file is corrupted.
My Html link:
<td> Download</td>
My url pattern links into a view:
url(r'^download/$', views.DownloadPdf),
My FileField is like this:
upload_pdf = models.FileField()
Following snippet code is the view that downloads a corrupted pdf:
def DownloadPdf(request):
filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf'
response = HttpResponse(content_type='application/pdf')
fileformat = "pdf"
response['Content-Disposition'] = 'attachment;
filename=thisismypdf'.format(fileformat)
return response
So, what I have to do to make it working ?
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/pdf")
response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
return response
#Sergey Gornostaev 's code just work perfect, but i post below my code because it is a aproach in a differect way.
I correct a little bit my code:
def DownloadPdf(request):
path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf'
f = open(path_to_file, 'r')
myfile = File(f)
response = HttpResponse(myfile, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename=filename'
return response
But only in pdf file ( works with txt files ) gives me that error:
'utf-8' codec can't decode byte 0xe2 in position 10

Serving Excel(xlsx) file to the user for download in Django(Python)

I'm trying create and serve excel files using Django. I have a jar file which gets parameters and produces an excel file according to parameters and it works with no problem. But when i'm trying to get the produced file and serve it to the user for download the file comes out broken. It has 0kb size. This is the code piece I'm using for excel generation and serving.
def generateExcel(request,id):
if os.path.exists('./%s_Report.xlsx' % id):
excel = open("%s_Report.xlsx" % id, "r")
output = StringIO.StringIO(excel.read())
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
args = ['ServerExcel.jar', id]
result = jarWrapper(*args) # this creates the excel file with no problem
if result:
excel = open("%s_Report.xlsx" % id, "r")
output = StringIO.StringIO(excel.read())
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
return HttpResponse(json.dumps({"no":"excel","no one": "cries"}))
I have searched for possible solutions and tried to use File Wrapper also but the result did not changed. I assume i have problem with reading the xlsx file into StringIO object. But dont have any idea about how to fix it
Why on earth are you passing your file's content to a StringIO just to assign StringIO.get_value() to a local variable ? What's wrong with assigning file.read() to your variable directly ?
def generateExcel(request,id):
path = './%s_Report.xlsx' % id # this should live elsewhere, definitely
if os.path.exists(path):
with open(path, "r") as excel:
data = excel.read()
response = HttpResponse(data,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
# quite some duplication to fix down there
Now you may want to check weither you actually had any content in your file - the fact that the file exists doesn't mean it has anything in it. Remember that you're in a concurrent context, you can have one thread or process trying to read the file while another (=>another request) is trying to write it.
In addition to what Bruno says, you probably need to open the file in binary mode:
excel = open("%s_Report.xlsx" % id, "rb")
You can use this library to create excel sheets on the fly.
http://xlsxwriter.readthedocs.io/
For more information see this page. Thanks to #alexcxe
XlsxWriter object save as http response to create download in Django
my answer is:
def generateExcel(request,id):
if os.path.exists('./%s_Report.xlsx' % id):
with open('./%s_Report.xlsx' % id, "rb") as file:
response = HttpResponse(file.read(),content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
# quite some duplication to fix down there
why using "rb"? because HttpResponse class init parameters is (self, content=b'', *args, **kwargs), so we should using "rb" and using .read() to get the bytes.

Categories

Resources