Skip to content

Instantly share code, notes, and snippets.

@K4zuki
Last active April 30, 2019 13:57
Show Gist options
  • Save K4zuki/269e80b16a7a1747c957a2ea0d83dc14 to your computer and use it in GitHub Desktop.
Save K4zuki/269e80b16a7a1747c957a2ea0d83dc14 to your computer and use it in GitHub Desktop.
Table column spanning post processor for a docx file
import docx
"""
Col span
+----+----+----+----+
|hoge|piyo|foo |bar |
+----+----+----+----+
|baz | |foo |bar |
+----+----+----+----+
|baz | | |bar |
+----+----+----+----+
|
V
+----+----+----+----+
|hoge|piyo| | |
+----+----+foo + +
| | | |bar |
+baz +----+----+ +
| | | | |
+----+----+----+----+
"""
filename = "filename.docx"
doc = docx.Document(filename)
for t in doc.tables:
for col in range(len(t.columns)):
for cell in t.column_cells(col):
text = cell.text
if text:
for next_cell in t.column_cells(col)[1:]:
next_text = next_cell.text
if next_text == text:
cell.merge(next_cell)
cell.text = text
else:
continue
doc.save(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment