Festlegen der Schriftgröße für Text und Tabellen mit dem Styles-Ansatz mit der Python-Docx-Bibliothek
Posted: 21 May 2025, 13:54
Ich verwende die Python-Docx-Bibliothek, um eine DOCX-Datei zu erstellen, die gleich danach Text und eine Tabelle enthält. Ich möchte die Textgröße auf 12 und die Tabellengröße mit Styles auf 9 Punkt einstellen. Aber die Größe des gesamten Textes, einschließlich des Textes in den Tabellenzellen, ist auf 12 gesetzt. Ich weiß, dass ich einen anderen Loop -basierten -Ansatz verwenden kann, um dieses Problem zu lösen, aber ich verwende es gerne Stile. Ist das möglich? /> Style-Ansatz (er funktioniert nicht) < /p>
Andere Loop-basierte Ansatz, der einwandfrei funktioniert, aber ich mag es:
Code: Select all
import random
from docx import Document
from docx.shared import Pt
doc = Document()
normal_style = doc.styles['Normal']
normal_style.font.size = Pt(12) # SETTING FONT SIZE 12 FOR TEXT
paragraph = doc.add_paragraph("This is some introductory text.", style='Normal')
num_rows = 5
num_cols = 4
table = doc.add_table(rows=num_rows, cols=num_cols)
for row in table.rows:
for cell in row.cells:
cell.text = str(random.randint(1, 100))
table.style = 'TableGrid'
table_grid_style = doc.styles['TableGrid']
table_grid_style.font.size = Pt(9) # SETTING FONT SIZE 9 FOR TABLES!
doc.save('random_table_with_intro_text.docx')
Code: Select all
import random
from docx import Document
from docx.shared import Pt
doc = Document()
paragraph = doc.add_paragraph("This is some introductory text.")
run = paragraph.runs[0]
run.font.size = Pt(12)
num_rows = 5
num_cols = 4
table = doc.add_table(rows=num_rows, cols=num_cols)
for row in table.rows:
for cell in row.cells:
paragraph = cell.paragraphs[0]
run = paragraph.add_run(str(random.randint(1, 100)))
run.font.size = Pt(9)
table.style = 'TableGrid'
doc.save('random_table_with_intro_text.docx')
< /code>
Wenn ich den Code, der den Text oberhalb der Tabelle hinzufügtimport random
from docx import Document
from docx.shared import Pt
doc = Document()
num_rows = 5
num_cols = 4
table = doc.add_table(rows=num_rows, cols=num_cols)
for row in table.rows:
for cell in row.cells:
cell.text = str(random.randint(1, 100))
table.style = 'TableGrid'
table_grid_style = doc.styles['TableGrid']
table_grid_style.font.size = Pt(9) # SETTING FONT SIZE 9 FOR TABLES!
doc.save('random_table_with_intro_text.docx')