Skip to content

IndexError when adding table #514

Open
@lc-thomas

Description

@lc-thomas

I'm opening a docx, and trying to add a table but python-docx crashed with this message :

Traceback (most recent call last):
  File "styler.py", line 4, in <module>
    document.add_table(rows=10,cols=10)
  File "/usr/local/lib/python3.6/site-packages/docx/document.py", line 99, in add_table
    table = self._body.add_table(rows, cols, self._block_width)
  File "/usr/local/lib/python3.6/site-packages/docx/document.py", line 184, in _block_width
    section = self.sections[-1]
  File "/usr/local/lib/python3.6/site-packages/docx/section.py", line 25, in __getitem__
    sectPr = self._document_elm.sectPr_lst[key]
IndexError: list index out of range

Looking at the code it seems that if there are no sections in the document, the library crashes.

So I created a section before creating the table :

from docx import Document

document = Document('report-3.docx')
document.add_section()
document.add_table(rows=10,cols=10)

But it crashes again :

Traceback (most recent call last):
  File "styler.py", line 6, in <module>
    document.add_table(rows=10,cols=10)
  File "/usr/local/lib/python3.6/site-packages/docx/document.py", line 99, in add_table
    table = self._body.add_table(rows, cols, self._block_width)
  File "/usr/local/lib/python3.6/site-packages/docx/document.py", line 186, in _block_width
    section.page_width - section.left_margin - section.right_margin
TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'

Isn't there a way to add a style to the document without adding a table.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions