Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Скриптовые языки программирования > Python
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 20.02.2019, 12:13   #1
Mr.Overlord
Пользователь
 
Регистрация: 06.02.2019
Сообщений: 17
По умолчанию python3+ docx

Господа подскажите пожалуйста как при формировании doxc документа через python регулировать междустрочный интервал?
использую модуль docx.
просто получается не очень красиво: после заголовка отступа нет, а в параграфе он огромный и это бросается в глаза. Принтскрин прилагаю.
Нужно сделать так, что бы между заголовком и параграфом появился интервал. Заранее благодарен.
Изображения
Тип файла: jpg docx.jpg (12.4 Кб, 160 просмотров)
Mr.Overlord вне форума Ответить с цитированием
Старый 20.02.2019, 12:21   #2
p51x
Старожил
 
Регистрация: 15.02.2010
Сообщений: 15,695
По умолчанию

https://python-docx.readthedocs.io/e...user/text.html
p51x вне форума Ответить с цитированием
Старый 20.02.2019, 13:56   #3
Mr.Overlord
Пользователь
 
Регистрация: 06.02.2019
Сообщений: 17
По умолчанию

Цитата:
Сообщение от p51x Посмотреть сообщение
Спасибо конечно, но теперь я совсем заблудился. Вот например на примере положения текста

from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
document = Document()
paragraph = document.add_paragraph()
paragraph_format = paragraph.paragraph_format
paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
paragraph_format.alignment('qwe')

document.save('demoless.docx')

данный код даст ошибку TypeError: 'EnumValue' object is not callable
уже и так и эдак попробовал. Что не так?

Последний раз редактировалось Mr.Overlord; 20.02.2019 в 13:58.
Mr.Overlord вне форума Ответить с цитированием
Старый 20.02.2019, 13:58   #4
Mr.Overlord
Пользователь
 
Регистрация: 06.02.2019
Сообщений: 17
По умолчанию

а если написать не paragraph_format.alignment('qwe'), а document.add_paragraph("qwe") то всё будет ок, но выравнивания не произойдет.......
Mr.Overlord вне форума Ответить с цитированием
Старый 20.02.2019, 14:02   #5
p51x
Старожил
 
Регистрация: 15.02.2010
Сообщений: 15,695
По умолчанию

Код:
paragraph_format.alignment('qwe')
А что вы хотели сделать этой строкой? Это же просто поле, оно не вызывается как функция.

Цитата:
document.add_paragraph("qwe") то всё будет ок, но выравнивания не произойдет.......
Вы после того, как это написали, свойство то изменили?
p51x вне форума Ответить с цитированием
Старый 20.02.2019, 14:06   #6
Mr.Overlord
Пользователь
 
Регистрация: 06.02.2019
Сообщений: 17
По умолчанию

Цитата:
Сообщение от p51x Посмотреть сообщение
Код:
paragraph_format.alignment('qwe')
А что вы хотели сделать этой строкой? Это же просто поле, оно не вызывается как функция.


Вы после того, как это написали, свойство то изменили?
нет, не изменил. Если честно не совсем понимаю как его изменить. Запутался в общем совсем...
Mr.Overlord вне форума Ответить с цитированием
Старый 20.02.2019, 14:08   #7
Mr.Overlord
Пользователь
 
Регистрация: 06.02.2019
Сообщений: 17
По умолчанию

paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
print(paragraph_format.alignment) вижу что это выравнивание по правому краю, но как применить это к параграфу?
Mr.Overlord вне форума Ответить с цитированием
Старый 20.02.2019, 15:35   #8
Mr.Overlord
Пользователь
 
Регистрация: 06.02.2019
Сообщений: 17
По умолчанию

Неужели мой вопрос настолько сложный, что никто не знает ответа?
Mr.Overlord вне форума Ответить с цитированием
Старый 21.02.2019, 09:34   #9
Mr.Overlord
Пользователь
 
Регистрация: 06.02.2019
Сообщений: 17
По умолчанию Решено

Вопрос решен, если кому интересно вот код:


Код:
from docx import Document
from docx.shared import RGBColor,Inches,Pt,Length
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_TAB_ALIGNMENT, WD_TAB_LEADER  # There will be abnormal red underscores, but they can be used normally.
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

document = Document()

# ===============================Paragraph Operations = 
document.add_heading('This is my title', 0)  # Add a title, but under this heading there will be a horizontal line.

# Setting the font
document.styles['Normal'].font.name = u'Blackbody'  # Can be replaced by any font in word.
p = document.add_paragraph()

# Set text alignment
p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # Paragraph text middle setting
# print(p.paragraph_format.alignment) # Print alignment

# Set the color and font size of paragraphs.
run = p.add_run(u'Paragraph text I added') # Зоздание заголовка параграфа
run.font.color.rgb = RGBColor(54, 95, 145)  # Цвет заголовка параграфа
run.font.size = Pt(80)  # Размер шрифта заголовка

# ==========Indent default left = = = = = = = = = =
paragraph = document.add_paragraph()
paragraph.add_run(
    'Indentation is specified using a Length value, such as Inches, Pt, or Cm. Negative values are valid and cause the paragraph to overlap the margin by the specified amount. A value of None indicates the indentation value is inherited from the style hierarchy. Assigning None to an indentation property removes any directly-applied indentation setting and restores inheritance from the style hierarchy:')
paragraph_format = paragraph.paragraph_format
# print(paragraph_format.left_indent)
# paragraph_format.left_indent = Inches(0.5) # Set to 0.5 units is cm, the default number is positive, indent to the right, negative, then move to the left.
# print(paragraph_format.left_indent)
# print(paragraph_format.left_indent.inches)

# Right indentation
# print(paragraph_format.right_indent)
paragraph_format.right_indent = Pt(24)
# print(paragraph_format.right_indent)
# print(paragraph_format.right_indent.pt) # Note: This is lowercase.

# text-indent
# print(paragraph_format.first_line_indent)
paragraph_format.first_line_indent = Inches(0.25)
# print(paragraph_format.first_line_indent)
# print(paragraph_format.first_line_indent.inches)

# ==========Tab = = = = = = = = = = =
"""
Tab stops determining the rendering of tabs in paragraph text.In particular, it specifies the text behind the tab character.Starting position, how it will be aligned with that position."""
tab_stops = paragraph_format.tab_stops
tab_stop = tab_stops.add_tab_stop(Inches(1.5))
# print(tab_stop.position)
# print(tab_stop.position.inches)

# Default left alignment, but by providing WD_TAB alignment enumeration leader characters default to spaces, but by providing WD_TAB leadership enumeration
tab_stop = tab_stops.add_tab_stop(Inches(1.5), WD_TAB_ALIGNMENT.RIGHT, WD_TAB_LEADER.DOTS)  # leaderPreamble
# print("alignment:",tab_stop.alignment,',leader:',tab_stop.leader)

# ==========Paragraph spacing = = = = = = = = = = =
# print(paragraph_format.space_before,paragraph_format.space_after)
paragraph_format.space_before = Pt(18) # Отступ от заголовка до параграфа
# print(paragraph_format.space_before.pt)
paragraph_format.space_after = Pt(120) # отступ от параграфа до таблицы
# print(paragraph_format.space_after.pt)

# ==========Row spacing = = = = = = = = = = =
# print(paragraph_format.line_spacing)
# print(paragraph_format.line_spacing_rule)
paragraph_format.line_spacing = Pt(18) # интервал строк внутри параграфа
# print(paragraph_format.line_spacing)
# print(paragraph_format.line_spacing_rule)
# paragraph_format.line_spacing = 1.75 # 1.75Doubling spacing
# print(paragraph_format.line_spacing)
# print(paragraph_format.line_spacing_rule)

# ==========Paging = = = = = = = = = = =

# print(paragraph_format.keep_together)
paragraph_format.keep_with_next = True
# print(paragraph_format.keep_with_next)
paragraph_format.page_break_before = False
# print(paragraph_format.page_break_before)


# ===============================Add picture = = = = = he picture and python file are not in the same folder, the file address should be filled.
## The picture is left aligned by default. To make the image center centered, a new object is needed.
#last_paragraph = document.paragraphs[-1]  # Paragraph attribute, representing three rows per row, -1 is the last line.
#last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # Picture centered settings

# ===============================Add form = = = = = = 
rows = 3
cols = 3
table = document.add_table(rows=rows, cols=cols, style="Table Grid")  # Add 2 rows and 3 columns to the table.
"""
There are many forms of style. By default, tables are not framed.The Table Grid format is an ordinary black border table, with more table styles.It can be Baidu. However, we often hope that the form will be more drifting.A bright modification, such as the width of a column in a custom table.The height of the table."""

# Set table width
# table.autofit = False # Closing the adaptive width of the table, which is actually executed in conjunction with the following two statements, can be omitted
# col = table.columns[0] # Get form first columns
# col.width = Inches(3)  # The width of table first is set to Inches (5). By default, tables are automatically adapted to document width.

# Set table height
for i in range(rows):  # Traverse all rows of a table
    tr = table.rows[i]._tr  # Get every row of the form
    trPr = tr.get_or_add_trPr()  # Get or add table row attributes
    trHeight = OxmlElement('w:trHeight')  # Get high attribute
    trHeight.set(qn('w:val'), "450")  # Set height
    trPr.append(trHeight)  # Add a high attribute to the form. The height of each row of the form is set. 450, this value can be modified arbitrarily.

# Add text to the table
arr = [u'Serial number', u'type', u'Detailed description']
arr2 = ['1', 'python', 'list']
arr3 = ['2', 'java', 'array']


# heading_cells = table.rows[0].cells  # Set the first row of the form to the table header.
# row2 = table.rows[1].cells
# for i in range(cols):  # colsNumber of columns for tables
#
#
#
#     # Head
#     p = heading_cells[i].paragraphs[0]  # Using paragraph function to add text
#     run = p.add_run(arr[i])  # Put the header in an array so that it can be easily assigned.
#     p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER  # Setting in center, the default is left alignment.
#
#     # Content first line
#     r2 = row2[i].paragraphs[0]
#     r2.add_run(arr2[i])
#     r2.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER  # Setting in center, the default is left alignment.


# Encapsulation function
def insert_data(num, cols, list):
    """
    :param num: The first few rows of the formParam cols: table numberParam list: data: return:"""
    row = table.rows[num - 1].cells  # Gets a row to the form.
    for i in range(cols):  # Traverse table columns
        r = row[i].paragraphs[0]
        r.add_run(list[i])
        r.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # Setting in center, the default is left alignment.


insert_data(1, cols, arr)
insert_data(2, cols, arr2)
insert_data(3, cols, arr3)

# The following two are not recommended, which will cause confusion in the form.
# Assign directly to a cell in the table.
# table.cell(1, 1).text = 'c'  # Set the text in the j column of the I row of the form, and the default text is left aligned in the table.
# table.cell(1, 2).text = 'Array (hard)

# Add rows at the bottom of the table.
# table.add_row()


document.save('test.docx')

Последний раз редактировалось Serge_Bliznykov; 21.02.2019 в 10:19.
Mr.Overlord вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Числа Фибоначчи на Python3 NekkittAY Python 2 18.06.2018 14:32
Задачка. Python3+. HiFull Общие вопросы по программированию, компьютерный форум 1 07.04.2018 19:17
python3 + postgresql 25-й кадр Python 0 01.03.2018 13:49
Python3 АнтонПинигин Помощь студентам 7 22.08.2017 18:38
[Python3]Многомерные массивы Sna1L Python 1 31.03.2012 04:37