繁体   English   中英

有关使用Python docx包向Word文档添加边框的查询

[英]A query about adding borders using Python docx Package to a word document

我试图用Python编写一个程序,该程序从Excel文件中获取数据并使用它来创建Word文件。 例如,考虑下面的Excel文件,名为Problems.xlsx 在此处输入图片说明

我希望为该Excel文件中给出的所有13个问题创建一个名为:(书ID)-(章ID)-(问题ID)的文件。 每个文件应如下所示:

忽略文件名Docume nt1.docx。 它应该是52289-9.2-59PS.docx。 但是请注意,第一行包含一个Bottom Border字样 ,左侧的文件名,公司名称(恒定)和今天的日期。

我在将边框添加到文档以及更改字体大小和名称时遇到了麻烦。 这是我到目前为止编写的代码。

from openpyxl import load_workbook
from docx import Document
from time import strftime
from docx.shared import Pt
#Accessing data from excel file. 
ws=load_workbook(filename="Problems.xlsx")
sheet=ws.get_sheet_by_name('Sheet2')
for i in range(2,15):
    fileName=""
    for j in range(1,4):
        if j!=3:
            fileName=fileName+str(sheet.cell(row=i,column=j).value)+"-"
        else:
            fileName=fileName+str(sheet.cell(row=i,column=j).value)
    #Now we have the file names, so let's make a file  
    document=Document()
    run=document.add_paragraph().add_run()
    font=run.font
    font.name="Times New Roman"
    font.size=12
    date=strftime("%d/%m/%Y")
    document.add_paragraph(fileName+"                                                                                           AID: 1112|"+date)
    document.add_paragraph("--------------------------------------------------------------------------------------------------------------------")
    #Saving the document with the fileName
    document.save(fileName+".docx")

上面的代码使用正确的名称创建文件,但是存在两个关键问题:

  1. 字体仍然是Calibri而不是Times New Roman,字体大小是11而不是12。
  2. 我现在添加了虚线,但是我真的很想有一个底边框,为此,您通常单击红色圆圈中的按钮。

经过反复试验,以下代码可以正常工作并修复我在“问题”中提到的两个问题。

from openpyxl import load_workbook
from docx import Document
from time import strftime
from docx.shared import Pt
#Accessing data from excel file. 
ws=load_workbook(filename="Problems.xlsx")
sheet=ws.get_sheet_by_name('Sheet2')
for i in range(2,15):
    fileName=""
    for j in range(1,4):
        if j!=3:
            fileName=fileName+str(sheet.cell(row=i,column=j).value)+"-"
        else:
            fileName=fileName+str(sheet.cell(row=i,column=j).value)
    #Now we have the file names, so let's make a file  
    document=Document()
    style=document.styles['Normal']
    font=style.font
    font.name="Times New Roman"
    font.size=Pt(12)
    date=strftime("%d/%m/%Y")
    font.underline=True
    document.add_paragraph(fileName+"                                                                       AID: 1112|"+date,style='Normal')
    #Saving the document with the fileName
    document.save(fileName+".docx")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM