view.py the file which process the POST request.
This app takes one excel sheet and xml file are argument , the xml contains some meta about the excel cell location. File its create a xml file in the current directory . I want to assign this file reference to a anchor tag download link in template. Hopefully this explain the problem.
from django.shortcuts import render
import openpyxl
import xmltodict
import collections
def deep_convert_dict(layer):
to_ret = layer
if isinstance(layer, collections.OrderedDict):
to_ret = dict(layer)
try:
for key, value in to_ret.items():
to_ret[key] = deep_convert_dict(value)
except AttributeError:
pass
return to_ret
def index(request):
if "GET" == request.method:
return render(request, 'myapp/index.html', {})
else:
excel_file = request.FILES["excel_file"]
xml_file = request.FILES["xml_file"]
#print(xml_file)
print(excel_file)
# you may put validations here to check extension or file size
wb = openpyxl.load_workbook(excel_file,data_only=True)
# getting all sheets
sheets = wb.sheetnames
print(sheets)
# getting a particular sheet
sheet = wb["Paydoc"]
file1 = open('reelset.xml','a')
doc = {}
doc = xmltodict.parse(xml_file.read())
dict_1 =deep_convert_dict(doc)
print(dict_1)
for key, value in dict_1.items() :
for key1, value1 in value.items() :
x = '\n<'+key1+'>\n'
file1.write(x)
for key2, value2 in value1.items() :
print (key2)
reel1 ='\t<Reel ReelIndex="'+key2[-1]+'">'+'\n\t\t'+'<Elements>'+'\n'
coloumn = value2['Coloumn']
startrow = int (value2['StartIndex'][1:-1])
endrow = int (value2['StopIndex'][1:-1])
count1 = 0
while(startrow < endrow):
c = sheet[coloumn[1:-1]+str(startrow)]
strx = '\t\t\t'+'<Element id='
strx = strx + '"'+str(count1)+'">'+str(c.value).upper()+'</Element>'+ '\n'
reel1 = reel1 + strx
strx = ''
startrow = startrow + 1
count1 = count1 + 1
reel1 = reel1 + '\t\t</Elements>'+'\n'+ '\t</Reel>\n'
print(reel1)
file1.write(reel1)
reel1 = ''
y = '</'+key1+'>'
file1.write(y)
file1.close()
import os
cwd = os.getcwd()
print(cwd)
file2 = open('./reelset.xml','r')
data = file2.read()
file2.close()
return render(request, 'myapp/index.html', {"posts":data})
HTML template:
<html>
<head>
<title>
REELSET CREATION WEB TOOL
</title>
</head>
<body style="margin-top: 30px;margin-left: 30px;">
<form action="{% url "myapp:index" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>PLEASE UPLOAD MATH EXCEL SHEET</p>
<input type="file"
title="Upload excel file"
name="excel_file"
style="border: 1px solid black; padding: 5px;"
required="required">
<p></p>
<p>PLEASE UPLOAD REELSET XML CONFIGURATION META DATA</p>
<input type="file"
title="Upload xml file"
name="xml_file"
style="border: 1px solid black; padding: 5px;"
required="required">
<p>
<input type="submit"
value="Upload"
style="border: 1px solid green; padding:5px; border-radius: 2px; cursor: pointer;">
</form>
<p></p>
<hr>
{% for row in excel_data %}
{% for cell in row %}
{{ cell }}
{% endfor %}
<br>
{% endfor %}
{{posts|escape }}
</body>
</html>