Reputation: 43
I want to read data from a ms excel file and edit an existing words document using the data from excel to fill in bookmarks and then save it as a pdf. So far I have been able to read to data successfully using openpyxl but I'm struggling with the editing and saving part. It would be great if someone can help.
my code:
from django.shortcuts import render
from django.http import HttpResponse
import openpyxl
from reportlab.pdfgen import canvas
import io
from io import BytesIO
def index(request):
if "GET" == request.method:
return render(request, 'letters/index.html', {})
else:
excel_file = request.FILES["excel_file"]
# you may put validations here to check extension or file size
wb = openpyxl.load_workbook(excel_file)
# getting a particular sheet by name out of many sheets
worksheet = wb.sheetnames
if 'sheet name' in wb.sheetnames:
sheet = wb['sheet name']
print(worksheet)
excel_data = list()
# iterating over the rows and
# getting value from each cell in row
for name in wb.sheetnames:
sheet = wb[name]
first = False
for row in sheet.iter_rows():
row_data = list()
for cell in row:
row_data.append(str(cell.value))
print (row_data)
if first == False:
pass
else:
buffer = io.BytesIO()
p = canvas.Canvas(buffer)
f = open("media/template.docx", "w+")
for x in range (5):
def BookMarkReplace():
f.Bookmark = name,
string = row_data[0])
{
Admission = row_data[2]
p.drawString(doc)
p.showPage()
p.save()
response ['Content-Disposition'] = 'attachment;filename=Admission.docx'
return response
first = True
excel_data.append(row_data)
return render(request, 'letters/index.html', {"excel_data":excel_data})
I'm not having any luck with this method. Does anyone know how to do this or any other way of doing this.
Upvotes: 1
Views: 450
Reputation: 43
Solved it!!! I used python-doxc to edit my word documents. I still couldn'f figure out how to use bookmarks, but instead I replaced the parts I want to edit like so:
for paragraph in document.paragraphs:
if 'Name of the student : ' in paragraph.text:
paragraph.text = 'Name of the student : ' + Name
Then I used pypandoc to covnvert them to pdfs.
pypandoc.convert_file('template.docx', 'pdf', outputfile='S' + ' ' + Name + '.pdf')
Upvotes: 1