Главное Авторские колонки Вакансии Вопросы
1 392 0 В избр. Сохранено
Авторизуйтесь
Вход с паролем

Как создавать документы Word в Python

В этой статье рассказывается о том, как создать документ Word с помощью библиотеки Python Word.
Мнение автора может не совпадать с мнением редакции

Когда речь заходит о создании документов, в частности файлов Word, Python предлагает множество библиотек, которые упрощают этот процесс и повышают эффективность. Эти библиотеки позволяют разработчикам легко создавать, изменять и манипулировать документами Word, удовлетворяя самые разные требования — от простых текстовых документов до сложных форматированных отчетов. Выбор правильной библиотеки Python для создания файлов Word имеет решающее значение для успеха проекта.

За последние несколько месяцев я попробовал обычные коммерческие библиотеки и библиотеки с открытым исходным кодом, представленные на рынке, и, основываясь на личном опыте, считаю Spire.Doc for Python одной из лучших библиотек. Она предоставляет полный набор инновационных API, позволяя программистам с легкостью генерировать, изменять и извлекать содержимое из документов Word.

1.Создание документа Word

2.Добавление изображений в документ Word

3.Добавление текстовых полей в документ Word

4.Создание таблиц в документе Word

5.Создание списков в документе Word

6.Загрузка документа Word

Библиотека для работы с текстом на Python

С помощью Spire.Doc вы можете создавать новые документы Word с нуля, загружать существующие документы, выполнять различные операции с документами, такие как добавление или удаление разделов, абзацев, таблиц, изображений, заголовков, колонтитулов и многое другое.

Вы можете установить Spire.Doc for Python в свое Python-приложение, выполнив следующую команду pip.

pip install Spire.Doc

Классы и методы для работы с документами Word

Spire.Doc — это объектно-ориентированный компонент обработки Word, позволяющий разработчикам управлять различными элементами документа Word с помощью всего нескольких строк кода. Номенклатура классов, методов и свойств проста и понятна. Имея базовое представление о структуре и элементах документов Word, пользователи смогут без труда использовать эти функциональные возможности. В следующей таблице приведены основные классы и методы Spire.Doc.


Шаги по созданию документа Word в Python

1.Импортируйте модули библиотеки Spire.Doc.

2.Создайте объект Document.

3.Добавьте раздел в документ.

4.Добавьте в раздел абзац.

5.Добавьте текст, изображения или другие элементы в абзац.

6.Сохраните документ в файл Doc или Docx.

Разобравшись с основными понятиями, давайте изучим шесть фрагментов кода, чтобы приобрести навыки создания документа Word. Эти фрагменты помогут вам добавить в документ абзацы (текст), рисунки, таблицы, текстовые поля и списки. Кроме того, вы узнаете, как загрузить существующий документ.

Создание документа Word в Python

from spire.doc import *

from spire.doc.common import *

# Create a Document object

doc = Document()

# Add a section

section = doc.AddSection()

# Set the page margins

section.PageSetup.Margins.All = 40

# Add a title

title = section.AddParagraph()

title.AppendText("Create a Word File in Python")

# Add two paragraphs

paragraph = section.AddParagraph()

paragraph.AppendText("Spire.Doc for Python is a professional Python library designed for developers to " +

«create, read, write, convert, compare and print Word documents in Python applications » +

«with fast and high-quality performance.»)

# Apply heading1 to the title

title.ApplyStyle(BuiltinStyle.Heading1)

# Create a style for the paragraph

style = ParagraphStyle(doc)

style.Name = «paraStyle»

style.CharacterFormat.FontName = «Arial»

style.CharacterFormat.FontSize = 13

doc.Styles.Add(style)

paragraph.ApplyStyle("paraStyle")

# Set the horizontal alignment of title and paragraph

title.Format.HorizontalAlignment = HorizontalAlignment.Center

paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left

# Set the after spacing

title.Format.AfterSpacing = 10

# Save to file

doc.SaveToFile("output/WordDocument.docx", FileFormat.Docx2019)

Добавление изображений в документ Word на Python

from spire.doc import *

from spire.doc.common import *

# Create a Document object

document = Document()

# Add a seciton

section = document.AddSection()

# Add a paragraph

paragraph = section.AddParagraph()

# Add an image to the specified paragraph

picture = paragraph.AppendPicture("C:\Users\Administrator\Desktop\mountain.jpg")

# Scale mage size

picture.Width = picture.Width*0.5

picture.Height = picture.Height*0.5

# Set text wrapping style

# picture.TextWrappingStyle = TextWrappingStyle.Square

# Save the result document

document.SaveToFile("InsertImage.docx", FileFormat.Docx)

document.Close()

Добавление текстовых полей в документ Word на Python

from spire.doc import *

from spire.doc.common import *

# Create a Document object

document = Document()

# Add a section

section = document.AddSection()

# Add a paragraph

paragraph = section.AddParagraph()

# Insert a textbox and set its wrapping style

textBox = paragraph.AppendTextBox(250, 80)

# Set the position of the textbox

textBox.Format.HorizontalOrigin = HorizontalOrigin.LeftMarginArea

textBox.Format.HorizontalPosition = 50

textBox.Format.VerticalOrigin = VerticalOrigin.Page

textBox.Format.VerticalPosition = 150

# Set the border style and fill color of the textbox

textBox.Format.LineColor = Color.get_DarkBlue()

textBox.Format.FillColor = Color.get_LightGray()

# Add a paragraph to textbox

para = textBox.Body.AddParagraph();

# Set alignment for the paragraph

para.Format.HorizontalAlignment = HorizontalAlignment.Left

# Insert text to textbox as the second paragraph

textRange = para.AppendText("This textbox contains additional information related to the topic of this document.")

# Set the font of the text

textRange.CharacterFormat.FontName = «Times New Roman»

textRange.CharacterFormat.FontSize = 18

textRange.CharacterFormat.Italic = True

# Set text wrapping style

# textBox.Format.TextWrappingStyle = TextWrappingStyle.Square

# Save the result document

document.SaveToFile("AddTextBox.docx", FileFormat.Docx)

Создание таблиц в документе Word на языке Python

from spire.doc import *

from spire.doc.common import *

# Create a Document object

doc = Document()

# Add a section

section = doc.AddSection()

# Add a table

table = section.Tables.Add()

# Set the border of table

table.TableFormat.Borders.BorderType = BorderStyle.Single

table.TableFormat.Borders.LineWidth = 1

table.TableFormat.Borders.Color = Color.get_Black()

# Add a row

row = table.AddRow(False, 3)

row.Height = 20.0

cell = row.Cells[0]

cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

paragraph = cell.AddParagraph()

paragraph.AppendText("First Name")

cell = row.Cells[1]

cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

paragraph = cell.AddParagraph()

paragraph.AppendText("Last Name")

cell = row.Cells[2]

cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

paragraph = cell.AddParagraph()

paragraph.AppendText("Age")

# Add another row

row = table.AddRow(False, 3)

row.Height = 20.0

cell = row.Cells[0]

cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

paragraph = cell.AddParagraph()

paragraph.AppendText("Nancy")

cell = row.Cells[1]

cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

paragraph = cell.AddParagraph()

paragraph.AppendText("Jones")

cell = row.Cells[2]

cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

paragraph = cell.AddParagraph()

paragraph.AppendText("25″)

# Save the document

doc.SaveToFile("CreateTable.docx", FileFormat.Docx2013)

doc.Close()

Создание списков в документе Word на языке Python

from spire.doc import *

from spire.doc.common import *

# Create a Document object

doc = Document()

# Add a section

section = doc.AddSection()

# Create a numbered list style

listStyle = ListStyle(doc, ListType.Numbered)

listStyle.Name = «numberedList»

listStyle.Levels[0].PatternType = ListPatternType.DecimalEnclosedParen

listStyle.Levels[0].TextPosition = 20;

doc.ListStyles.Add(listStyle)

# Add a paragraph

paragraph = section.AddParagraph()

paragraph.AppendText("Things to do today:")

paragraph.Format.AfterSpacing = 5.0

# Add a paragraph and apply the numbered list style to it

paragraph = section.AddParagraph()

paragraph.AppendText("Feed cat")

paragraph.ListFormat.ApplyStyle("numberedList")

paragraph.ListFormat.ListLevelNumber = 0

# Add the other two paragraphs and apply the numbered list style to them

paragraph = section.AddParagraph()

paragraph.AppendText("Wash car")

paragraph.ListFormat.ApplyStyle("numberedList")

paragraph.ListFormat.ListLevelNumber = 0

paragraph = section.AddParagraph()

paragraph.AppendText("Shopping")

paragraph.ListFormat.ApplyStyle("numberedList")

paragraph.ListFormat.ListLevelNumber = 0

# Save the document to file

doc.SaveToFile("CreateList.docx", FileFormat.Docx)

Загрузка документа Word в Python

from spire.doc import *

from spire.doc.common import *

# Create a Document object

doc = Document()

# Load an existing Word file

doc.LoadFromFile("C:\Users\Administrator\Desktop\input.docx")

# Edit the document

# Save to file

doc.SaveToFile("output.docx", FileFormat.Docx2019)

0
В избр. Сохранено
Авторизуйтесь
Вход с паролем
Комментарии
Выбрать файл
Блог проекта
Расскажите историю о создании или развитии проекта, поиске команды, проблемах и решениях
Написать
Личный блог
Продвигайте свои услуги или личный бренд через интересные кейсы и статьи
Написать

Spark использует cookie-файлы. С их помощью мы улучшаем работу нашего сайта и ваше взаимодействие с ним.