Уведомления

Группа в Telegram: @pythonsu

#1 Фев. 20, 2019 13:57:29

Sergey1990
Зарегистрирован: 2019-02-20
Сообщения: 5
Репутация: +  0  -
Профиль   Отправить e-mail  

python3 формирование файла docx

Здравствуйте, очень надеюсь на вашу помощь, потому как сломал всю голову. Необходимо сформировать docx файл. С этим проблем нет, но нужно сделать выравнивание некоторых абзацев. Прочитал кучу литературы. Дошел вот до чего.
Имеется простой код

from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
document = Document()
paragraph = document.add_paragraph()
paragraph_format = paragraph.paragraph_format

print(paragraph_format.alignment)
paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
print(paragraph_format.alignment) # ВИЖУ ЧТО ПОЛОЖЕНИЕ ТЕКСТА ДЕЙСТВИТЕЛЬНО = RIGHT(2)
document.add_paragraph(“hello world”)
document.save('demoless.docx')

При выполнении этого кода создается файл demoless.docx и содержит одну строчку hello world, но она соответственно не находится справа. Вопрос как paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT засунуть в document.add_paragraph(“hello world”) или как их подружить, что бы hello world был всё таки справа, как того и требует задача.
P.S. заранее благодарен!!!

Отредактировано Sergey1990 (Фев. 20, 2019 14:30:59)

Офлайн

#2 Фев. 21, 2019 08:42:48

Sergey1990
Зарегистрирован: 2019-02-20
Сообщения: 5
Репутация: +  0  -
Профиль   Отправить e-mail  

python3 формирование файла docx

Сам разобрался, Если кому неинтересно ниже приведен подробный код создания страницы с различным форматированием:

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 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
head = document.add_heading()
head.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
run1=head.add_run('This is my title', 0) # Вариант создания заголовка по центру
run1.font.size = Pt(100) # Размер шрифта заголовка
# Setting the font
document.styles.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 = = = = = = = = = = =
“”“
keep_togetherCauses the entire paragraph to appear on the same page, and if it would otherwise break between two pages, a page would be issued before the paragraph.Keep_with_next saves paragraphs on the same page as the next paragraph. For example, this can be used to keep the title of the section on the same page as the first paragraph of the section..Page_break_before places paragraphs at the top of the new page. This can be used in the chapter title to ensure that the chapter starts with the new page.Widow_control disconnects a page to avoid placing the first or last line of the paragraph with the rest of the paragraph.On a separate page.”“”
# 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 = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
#pic = document.add_picture('1.jpg', width=Inches(1.5)) # When the 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 # 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 # 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._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 =
arr2 =
arr3 =


# heading_cells = table.rows.cells # Set the first row of the form to the table header.
# row2 = table.rows.cells
# for i in range(cols): # colsNumber of columns for tables
#
#
#
# # Head
# p = heading_cells.paragraphs # Using paragraph function to add text
# run = p.add_run(arr) # 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.paragraphs
# r2.add_run(arr2)
# 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.cells # Gets a row to the form.
for i in range(cols): # Traverse table columns
r = row.paragraphs
r.add_run(list)
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')

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version