title: Is there a way to debug and/or validate Microsoft Word document XML generated by python-docx?
body: <p>I am building a simple framework for generating Microsoft Word document reports using the python-docx library. Occasionally, when I generate a document I run into a problem in which the docx file is generated successfully by python-docx, but then the docx file will not open in Microsoft Word and an error message like this is displayed: <a href="https://i.stack.imgur.com/ekWHa.png" rel="nofollow noreferrer">Microsoft Word 'Unspecified Error' Message</a></p>
  
  <p>By working through my code step by step - progressively inserting more and more content into the python-docx Document and then attempting to open the generated docx file after each content addition - I was able to identify the code which was causing the error. As it turned out, the error was caused when I attempted to insert an empty pandas dataframe using the code below:</p>
  
  <pre><code>def insert_as_table(df: pd.DataFrame, document: Document) -&gt; Document:
  
      # compute parameters
      n_rows = len(df) + 1
      n_cols = len(df.columns)
  
      # create table object
      table = document.add_table(rows=n_rows, cols=n_cols)
  
      # fill header cells with text
      for header_cell, col in zip(table.rows[0].cells, df.columns):
          header_cell.text = str(col)
  
      # fill cells with strings
      for i, row in df.iterrows():
          for table_cell, (j, data) in zip(table.rows[i + 1].cells, row.iteritems()):
              table_cell.text = str(data)
  
      return document
  </code></pre>
  
  <p>My solution was to add input validation - checking that the dataframe was not empty before attempting to insert it:</p>
  
  <pre><code>def insert_as_table(df: pd.DataFrame, document: Document) -&gt; Document:
  
      if df.empty:
          raise ValueError('df is empty. Cannot insert an empty dataframe as a table.')
  
      etc...
  </code></pre>
  
  <p>While this worked, the bug hunt process leads to my question: is there a way to debug and/or validate the Microsoft Word XML code that is generated by python-docx? In regards to validation, is there a way that I can validate that the docx file generated by python-docx is valid and will be able to be opened by Microsoft Word (without actually having to open it using Word)? In regards to debugging, is there a way that I can view and debug the docx XML code to identify where an issue is located (and perhaps obtain some clues as to where the issue is being generated in the Python code)? Such a tool or method would likely have saved me a significant amount of time in the bug hunt that I described above and perhaps will save me time in the future as well. Thanks much for your time and thoughts.</p>