狂自私

导航

python-docx的简单使用

安装docx库:

pip install python-docx

导入库:
import docx

新建一个空白文档:

word_doc = docx.Document()

新建一个段落:
paragraph=word_doc.add_paragraph('输变电在线监测装置可用率周报')

给这个段落设置黑体,2号格式:

for run in paragraph.runs:
        run.font.name = '黑体'
        run.element.rPr.rFonts.set(qn('w:eastAsia'),"黑体")
        run.font.size = Pt(22)  #二号

这里解释一下run和paragraph的关系:

paragraph包含一个或多个run,每个run表示一个范围,这个范围内的内容、格式和其他run里面的可以不同。这样一个段落里面就可以拥有不同格式的内容。最简单的应用就是段落里面的中西文字体样式不一样。

段落居中:

paragraph.alignment = docx.enum.text.WD_PARAGRAPH_ALIGNMENT.CENTER

设置段前段后(这里设置的为0):

paragraph.paragraph_format.space_befor=Pt(0)
paragraph.paragraph_format.space_after=Pt(0)

设置行距:

  单倍行距

  paragraph.paragraph_format.line_spacing=1

  paragraph.paragraph_format.line_spacing_rule=docx.enum.text.WD_LINE_SPACING.SINGLE

  多倍行距:

  paragraph.paragraph_format.line_spacing=1.5

  paragraph.paragraph_format.line_spacing_rule=docx.enum.text.WD_LINE_SPACING.MULTIPLE

缩进两字符:

paragraph.paragraph_format.first_line_indent=Pt(16*2)

这里的16表示字体大小。16表示的是3号字体。

两端对齐:

paragraph.alignment=docx.enum.text.WD_PARAGRAPH_ALIGNMENT.DISTRIBUTE

对同一个段落汇总的中文和西文设置不同字体:

def 区分字符串中的汉字和英文字符(text:str)->list:
    '''
    返回列表,按照text的顺序,对每一段做标志
    '''
    str_data=None
    if(len(text)>=2):
        ch = text[0]
        if(ord(ch)<=128):
            str_data=[{'内容':ch,"flag":0}]
        else:
            str_data=[{'内容':ch,"flag":1}]
        for ch in text[1:]:
            flag=None
            if(ord(ch)<=128):
                flag=0
            else:
                flag=1
            if(str_data[-1]["flag"] == flag):
                str_data[-1]["内容"]+=ch
            else:
                str_data.append({'内容':ch,"flag":flag})
    elif(len(text)==1):
        if(ord(text)<=128):
            str_data=[{'内容':text,"flag":0}]
        else:
            str_data=[{'内容':text,"flag":1}]
    else:
        str_data=[{'内容':text,"flag":1}]
    return str_data;
def 设置正文值以及正文样式(word_doc,text):
    '''
    非中文字符和符号设置为Times New Roman字体;中文字符设置为仿宋
    两端对齐,三号,首行缩进2字符
    '''
    str_data = 区分字符串中的汉字和英文字符(text)
    paragraph=word_doc.add_paragraph('')
    for text_dict in str_data:
        run = paragraph.add_run(text_dict['内容'])
        if(text_dict['flag']):
            #中文
            run.font.name = '仿宋'
            run.element.rPr.rFonts.set(qn('w:eastAsia'),"仿宋")
        else:
            run.font.name = 'Times New Roman'
            run.element.rPr.rFonts.set(qn('w:eastAsia'),"Times New Roman")
        run.font.size = Pt(16)  #三号

自动调整表格的列宽(但是还是没有word做得好):

def 自动调整单元格大小(table):
    '''
    先根据单元格内容调整单元格列宽,再根据页面可用宽度调整
    '''
    lenght_dict={}
    #初始化每一列的宽度为0
    列序号_list = list(range(len(table.columns)))
    for i in 列序号_list:
        lenght_dict[i]=0
    # 遍历表格,获取每一列的最大宽度(单位像素)
    for row in table.rows:
        for idx,cell in enumerate(row.cells):
            lenght_dict[idx]=max(len(cell.text)*12,lenght_dict[idx])
    总列宽=0
    for lenght in lenght_dict.values():
        总列宽+=lenght
    #依次计算每一列的列宽占比
    列宽占比_list = [lenght_dict[idx]/总列宽 for idx in 列序号_list]
    #A4纸宽21cm,常规页边距,左右各3.18cm,则可用长度为21-3.18*2=14.64cm
    页面可用长度=14.64
    for idx,col in enumerate(table.columns):
        l = Cm(页面可用长度*列宽占比_list[idx])
        col.width=l
    return ;

设置表格样式的示例:

def 设置表格样式(table):
    '''
    宋体,小四,首行加粗,段前段后0行,单倍行距,居中,设置所有边框,自动调整列宽
    '''
    #调整格式
    #设置表格第一行字体加粗
    for cell in table.rows[0].cells:
        cell.paragraphs[0].runs[0].bold=True
    #设置字体和字号为小四
    for row in table.rows:
        for cell in row.cells:
            设置单元格段落字体字号(cell)
            #单元格内容水平居中
            cell.vertical_alignment=docx.enum.table.WD_ALIGN_VERTICAL.CENTER
    #表格居中
    table.alignment = docx.enum.table.WD_TABLE_ALIGNMENT.CENTER
    table.autofit=False
    #设置边框
    设置表格网格线为黑色实线(table)
    自动调整单元格大小(table);

合并表格的单元格:

def 合并指定位置的单元格(table,坐标_list:list)->None:
    '''
    实际上是合并表格第二列的某些行的单元格
    '''
    for 坐标 in 坐标_list:
        start_cell = table.cell(坐标[0][0],坐标[0][1])
        end_cell = table.cell(坐标[1][0],坐标[1][1])
        #合并
        start_cell.merge(end_cell)
        start_cell.text=start_cell.text.split('\n')[0];

保存word文档:

word_doc.save(save_filepath)

执行完save后,好像是无需关闭,直接结束程序运行即可。

 


''' 设置表格所有单元格的四个边为0.5磅,黑色,实线 可以使用返回值,也可以不使用 ''' def 设置表格网格线为黑色实线(table_object:object): kwargs = { "top":{"sz": 4, "val": "single", "color": "#000000"}, "bottom":{"sz": 4, "val": "single", "color": "#000000"}, "left":{"sz": 4, "val": "single", "color": "#000000"}, "right":{"sz": 4, "val": "single", "color": "#000000"}, "insideV":{"sz": 4, "val": "single", "color": "#000000"}, "insideH":{"sz": 4, "val": "single", "color": "#000000"} } borders = docx.oxml.OxmlElement('w:tblBorders') for tag in ('bottom', 'top', 'left', 'right', 'insideV', 'insideH'): edge_data = kwargs.get(tag) if edge_data: any_border = docx.oxml.OxmlElement(f'w:{tag}') for key in ["sz", "val", "color", "space", "shadow"]: if key in edge_data: any_border.set(docx.oxml.ns.qn(f'w:{key}'), str(edge_data[key])) borders.append(any_border) table_object._tbl.tblPr.append(borders) return table_object ''' 设置标题样式 ''' def 设置标题样式为黑色宋体(heading_object:object): heading_object.alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.LEFT #左对齐 for run in heading_object.runs: run.font.name=u'宋体' #设置为宋体 #run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')#设置为宋体,和上边的一起使用 run.font.color.rgb = docx.shared.RGBColor(0,0,0)#设置颜色为黑色 return heading_object ''' 创建docx文档,将翻译结果和原文写入文档中 ''' def word(): my_word_doc = docx.Document() #打开一个空白文档 # for style in my_word_doc.styles: # print(style) heading = my_word_doc.add_heading(翻译结果["NAME"],level=2) #指定样式标题2 设置标题样式为黑色宋体(heading) heading = my_word_doc.add_heading("描述",level=3) #指定样式标题3 设置标题样式为黑色宋体(heading) for line in 翻译结果["SYNOPSIS"].split("\n"): my_word_doc.add_paragraph(line) for line in 翻译结果["DESCRIPTION"].split("\n"): my_word_doc.add_paragraph(line) heading = my_word_doc.add_heading("参数",level=3) #指定样式标题3 设置标题样式为黑色宋体(heading) #table = my_word_doc.add_table(rows=len(翻译结果["PARAMETERS"]), cols=3) #指定样式标题3;在末尾添加一个表 table = my_word_doc.add_table(rows=len(翻译结果["PARAMETERS"]), cols=2) #指定样式标题3;在末尾添加一个表 #table.style = my_word_doc.styles['Medium Grid 1'] 设置表格网格线为黑色实线(table) index=0 for key,value in 翻译结果["PARAMETERS"].items(): for line in key.split("\n"): cell = table.cell(index,0) cell.text += line for line in value.split("\n"): table.cell(index,1).text += line #table.cell(index,1).text = 帮助文件解析结果["PARAMETERS"][key] cell_paragraphs = table.cell(index,0).paragraphs for i in cell_paragraphs: i.alignment = docx.enum.text.WD_PARAGRAPH_ALIGNMENT.LEFT #左对齐 cell_paragraphs = table.cell(index,1).paragraphs for i in cell_paragraphs: i.alignment = docx.enum.text.WD_PARAGRAPH_ALIGNMENT.LEFT #左对齐 # table.cell(index,2).text = value # cell_paragraphs = table.cell(index,2).paragraphs # for i in cell_paragraphs: # i.alignment = docx.enum.text.WD_PARAGRAPH_ALIGNMENT.LEFT #左对齐 index += 1 heading = my_word_doc.add_heading("示例",level=3) #指定样式标题3 设置标题样式为黑色宋体(heading) for key,value in 翻译结果["Example"].items(): heading = my_word_doc.add_heading(key[0:-1],level=4) #指定样式标题4 设置标题样式为黑色宋体(heading) for line in value.split("\n"): my_word_doc.add_paragraph(line) my_word_doc.save(r"C:\Users\gyj\Downloads\temp.docx")

 

posted on 2023-05-03 08:28  狂自私  阅读(77)  评论(0编辑  收藏  举报