Python-docx - 如何更改 table 字体大小?
Python-docx - How to change table font size?
table = document.add_table(rows=1, cols=1)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
我必须将 table 中文本 'Qty' 的字体大小更改为一行一列,我该怎么做?
您需要获取单元格中的段落。来自 python-docx 的文档:
3.5.2 _Cell objects:
class docx.table._Cell (tc, parent)
paragraphs
List of paragraphs in the cell. A table cell is required to
contain at least one block-level element and end with a paragraph. By
default, a new cell contains a single paragraph. Read-only
参考:python-docx Documentation - Read the Docs
代码:
更改文本的字体大小'Qty'
paragraph =hdr_cells[0].paragraphs[0]
run = paragraph.runs
font = run[0].font
font.size= Pt(30) # font size = 30
要改变整个字体大小table:
for row in table.rows:
for cell in row.cells:
paragraphs = cell.paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
font = run.font
font.size= Pt(30)
参考如何访问table中的段落:Extracting data from tables
上面的解决方案真的很有帮助。我用了一段时间。但是我发现了一个小问题:time。随着您的 table 越来越大,您构建 table 所花费的时间也越来越长。所以我改进它。剪两圈。你在这里:
代码改全table
for row in table.rows:
for cell in row.cells:
paragraphs = cell.paragraphs
paragraph = paragraphs[0]
run_obj = paragraph.runs
run = run_obj[0]
font = run.font
font.size = Pt(30)
切两圈就省时间
基于 user7609283 的回答,这是一个将单元格设置为粗体的简短版本(单元格在应用格式之前必须包含文本,因为它会查找第一段):
row_cells = table.add_row().cells
row_cells[0].text = "Customer"
row_cells[0].paragraphs[0].runs[0].font.bold = True
table = document.add_table(rows=1, cols=1)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
我必须将 table 中文本 'Qty' 的字体大小更改为一行一列,我该怎么做?
您需要获取单元格中的段落。来自 python-docx 的文档:
3.5.2 _Cell objects:
class docx.table._Cell (tc, parent)paragraphs
List of paragraphs in the cell. A table cell is required to contain at least one block-level element and end with a paragraph. By default, a new cell contains a single paragraph. Read-only
参考:python-docx Documentation - Read the Docs
代码:
更改文本的字体大小'Qty'
paragraph =hdr_cells[0].paragraphs[0]
run = paragraph.runs
font = run[0].font
font.size= Pt(30) # font size = 30
要改变整个字体大小table:
for row in table.rows:
for cell in row.cells:
paragraphs = cell.paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
font = run.font
font.size= Pt(30)
参考如何访问table中的段落:Extracting data from tables
上面的解决方案真的很有帮助。我用了一段时间。但是我发现了一个小问题:time。随着您的 table 越来越大,您构建 table 所花费的时间也越来越长。所以我改进它。剪两圈。你在这里:
代码改全table
for row in table.rows:
for cell in row.cells:
paragraphs = cell.paragraphs
paragraph = paragraphs[0]
run_obj = paragraph.runs
run = run_obj[0]
font = run.font
font.size = Pt(30)
切两圈就省时间
基于 user7609283 的回答,这是一个将单元格设置为粗体的简短版本(单元格在应用格式之前必须包含文本,因为它会查找第一段):
row_cells = table.add_row().cells
row_cells[0].text = "Customer"
row_cells[0].paragraphs[0].runs[0].font.bold = True