i am trying to export a table with dynamic rows (quantity depends on user) to a Microsoft Word table using python-docx This is my code for the docx:
doc.add_heading("Findings Summary", level=1)
table_findings = doc.add_table(rows=0, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'ID'
hdr_cells[1].text = 'Description'
hdr_cells[2].text = 'Risk'
test_id1 = self.InformationOverviewTestIDLineEdit.text()
for row_index, row_data in enumerate(c.execute('SELECT Summary_Findings_Name, Summary_Findings_Desc, Summary_Findings_Risk FROM Findings_Summaries WHERE Test_ID=?', [test_id1])):
row_cells = table_findings.add_row().cells
row_cells[0].text = (row_data)
row_cells[1].text = (row_data)
row_cells[2].text = (row_data)
doc.add_page_break()
This is just the part of the code I need working, I have the rest working flawlessly. That was my first attempt and I thought that it'd be easier doing that way. Essentially, I want to loop the database looking for the Test_ID and extracting all the rows from that Database that contains the Test_ID searched. This Test_ID will be displayed in Line Edit on my PyQT5 code. Its the loop part I am struggling with. If i were to run that code as it is, it returns this error:
tuple index out of range
line 1080, in Extracting_Report
hdr_cells1[2].text = 'Risk'
IndexError: tuple index out of range
EDIT: I have managed to find the issue and this is the new code:
doc.add_heading("Findings Summary", level=1)
table_findings = doc.add_table(rows=1, cols=3)
hdr_cells1 = table_findings.rows[0].cells
hdr_cells1[0].text = 'ID'
hdr_cells1[1].text = 'Description'
hdr_cells1[2].text = 'Risk'
test_id1 = self.InformationOverviewTestIDLineEdit.text()
for row_index, row_data in enumerate(c.execute('SELECT Summary_Findings_Name, Summary_Findings_Desc, Summary_Findings_Risk FROM Findings_Summaries WHERE Test_ID=?', [test_id1])):
row_cells = table_findings.add_row().cells
row_cells[0].text = (row_data)
row_cells[1].text = (row_data)
row_cells[2].text = (row_data)
print(row_data)
However, now it prints the row_data but doesnt create the document and it should considering if i remove this block of code it creates a docx document fine
A table with zero rows has no cells. Try:
table_findings = doc.add_table(rows=1, cols=3)
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.