我正在尝试使用python docx在第一页中制作表格,但是当我尝试修改标题的字体大小时,表格大小也会改变,即使我尝试在表格中再添加一个字体大小 设置。我该怎么办?
def Firstpage():
titlename='Test'+' '+lastday
title = doc.add_paragraph()
title.add_run(titlename).bold=True
#title.style.font.size=Pt(20)
title.alignment=WD_ALIGN_PARAGRAPH.CENTER
filename=lastday+' '+'test.docx'
filepath = os.path.join(r'C:\Users\Administrator\Desktop\python test\update_test', filename)
doc.save(filepath)
def ShiftTable():
table = doc.add_table(rows=27, cols=6)
table.style='Table Grid'
table.style.font.size=Pt(2)
table.cell(0,0).text = "Shift"
table.cell(0,1).text = "Hour"
table.cell(0,2).text = "Parts Production"
table.cell(0,3).text = "Good Parts"
table.cell(0,4).text = "Bad Parts"
table.cell(0,5).text = "Average Cycle Time"
table.cell(1,0).text = "Morning Shift"
table.cell(1,1).text = "08AM - 09AM"
table.cell(2,1).text = "09AM - 10AM"
table.cell(3,1).text = "10AM - 11AM"
table.cell(4,1).text = "11AM - 12PM"
table.cell(5,1).text = "12PM - 01PM"
table.cell(6,1).text = "01PM - 02PM"
table.cell(7,1).text = "02PM - 03PM"
table.cell(8,0).text = "Shift Summary"
table.cell(9,0).text = "Afternoon Shift"
table.cell(9,1).text = "03PM - 04PM"
table.cell(10,1).text = "04PM - 05PM"
table.cell(11,1).text = "05PM - 06PM"
table.cell(12,1).text = "06PM - 07PM"
table.cell(13,1).text = "07PM - 08PM"
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(10)
Firstpage()
ShiftTable()
filename=lastday+' '+'test.docx'
filepath = os.path.join(r'C:\Users\Administrator\Desktop\python test\update_test', filename)
doc.save(filepath)
现在表格中的字体大小更改为10,但空单元格仍为20
答案 0 :(得分:0)
在运行级别应用字体大小。这是不同的"运行"段落中的文本可以有不同的大小。
您通常不应更改样式设置,除非您希望全局应用这些设置。在任何情况下,表格样式字体设置可能会也可能不会应用于它包含的所有文本。
如果要更改单个单元格的文本,则必须将该大小更改应用于其包含的所有运行。在你的情况下,你可以这样做:
cell = table.cell(0, 0)
cell.text = 'Shift'
cell_font = cell.text_frame.paragraphs[0].runs[0].font
cell_font.size = Pt(10)
确保您理解与样式有关的文档的这一部分:
http://python-docx.readthedocs.io/en/latest/user/styles-understanding.html和
http://python-docx.readthedocs.io/en/latest/user/styles-using.html