Как отключить интервал между ячейками в документе Word?Python

Программы на Python
Anonymous
Как отключить интервал между ячейками в документе Word?

Сообщение Anonymous »

У меня есть входной текстовый документ, в котором есть несколько таблиц с интервалом между ячейками, равным 0,02". Я хотел бы отключить этот интервал между ячейками (или установить его равным 0) с помощью приведенного ниже кода, который использует пакет python-docx. Однако когда я запускаю код для файла входного слова и открываю выходной файл, интервал между ячейками по-прежнему включен и равен 0,02.
Я включаю скриншот настройки в Г-жа Word, а также код Python:
Почему приведенный ниже код не приводит к нулевому интервалу между ячейками?

Код: Выделить всё

from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn

def disable_cell_spacing_in_tables(file_path, output_path):
"""
Disable cell spacing for all tables in the given Word document.

:param file_path: Path to the input Word document.
:param output_path: Path to save the modified Word document.
"""
# Open the Word document
doc = Document(file_path)

# Iterate through all tables in the document
for table in doc.tables:
tbl = table._element
tblPr = tbl.tblPr if tbl.tblPr is not None else OxmlElement('w:tblPr')
if tbl.tblPr is None:
tbl.append(tblPr)

# Disable cell spacing
tbl_cell_spacing = tblPr.find(qn('w:tblCellSpacing'))
if tbl_cell_spacing is not None:
tblPr.remove(tbl_cell_spacing)
tbl_cell_spacing = OxmlElement('w:tblCellSpacing')
tbl_cell_spacing.set(qn('w:w'), '0')
tbl_cell_spacing.set(qn('w:type'), 'dxa')
tblPr.append(tbl_cell_spacing)

# Save the modified document
doc.save(output_path)
print(f"Modified document saved to {output_path}")

if __name__ == "__main__":
input_file_path = 'input.docx'
output_file_path = 'output.docx'
disable_cell_spacing_in_tables(input_file_path, output_file_path)
Изображение


Подробнее здесь: https://stackoverflow.com/questions/790 ... d-document

Вернуться в «Python»