Python3处理文档

您所在的位置:网站首页 怎么在word里增加表格行数 Python3处理文档

Python3处理文档

2024-06-13 01:56| 来源: 网络整理| 查看: 265

利用python-docx自动生成表格

add_table()方法会返回一个Table对象。rows代表行数,cols代表列数;style代表样式,具体可以查看官方文档。

一、创建一个8行5列的表格

from docx import * doc=Document() table = doc.add_table(rows=8, cols=5) doc.save('table.docx')

上述代码就在word里插入了一个8行、5列的表格。(有8*5=40个cell) 在这里插入图片描述

生成的每个cell都是有“坐标”的,比如上面的表格左上角cell为(0,0),右下角cell为(7,4) Table()对象中报了对表格进行操作的方法和属性,如下:

add_column(width):添加列(需要设置列宽) add_row():添加行 cell(row_idx, col_idx):访问单个单元格 row_cells(row_idx):返回一个序列(行号为row_idx的行内所有单元格) column_cells(column_idx):返回一个序列(列号为column_idx的列内所有单元格) rows:返回的是_Rows对象,是一个包含了所有行(_Row对象)的列表 columns:返回的是_Columns对象,是一个包含了所有列(_Column对象)的列表 想要熟练使用python-docx操作Word文档:需要认识Table()、_Cell()、 _Row()、 _Rows() _Column() 和 _Columns()五个类。

二、设置表头 rows代表行数,rows[0]即第一行。hdr_cells = table.rows[0].cells,hdr_cells即第一行的所有单元格。

from docx import * doc=Document() table = doc.add_table(rows=8, cols=5) hdr_cells = table.rows[0].cells hdr_cells[0].text = '编号编号' hdr_cells[1].text = '漏洞名称' hdr_cells[2].text = '影响IP' hdr_cells[3].text = 'CVE ID' hdr_cells[4].text = '危险程度' doc.save('table.docx')

运行结果: 在这里插入图片描述

三、设置表格样式

上边的表格是默认的没有格式的,下边提供了两种设置表格边框的方式.

1、使用系统style

#方法一:创建表格时设置 doc=Document() table = doc.add_table(rows=8, cols=5,style =‘Table Grid’) doc.save('table.docx') #方法二:创建表格后,再设置 doc=Document() table = doc.add_table(rows=8, cols=5) table.style =‘Table Grid’ doc.save('table.docx')

运行结果: 在这里插入图片描述 2、自定义表格边框

#设置表格的边框 def set_cell_border(cell, **kwargs): """ Set cell`s border Usage: set_cell_border( cell, top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"}, bottom={"sz": 12, "color": "#00FF00", "val": "single"}, left={"sz": 24, "val": "dashed", "shadow": "true"}, right={"sz": 12, "val": "dashed"}, ) """ tc = cell._tc tcPr = tc.get_or_add_tcPr() # check for tag existnace, if none found, then create one tcBorders = tcPr.first_child_found_in("w:tcBorders") if tcBorders is None: tcBorders = OxmlElement('w:tcBorders') tcPr.append(tcBorders) # list over all available tags for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'): edge_data = kwargs.get(edge) if edge_data: tag = 'w:{}'.format(edge) # check for tag existnace, if none found, then create one element = tcBorders.find(qn(tag)) if element is None: element = OxmlElement(tag) tcBorders.append(element) # looks like order of attributes is important for key in ["sz", "val", "color", "space", "shadow"]: if key in edge_data: element.set(qn('w:{}'.format(key)), str(edge_data[key]))

调用该函数:

set_cell_border(hdr_cells[0], top={"sz": 12, "val": "single", "color": "#FF0000"}, bottom={"sz": 12, "val": "single", "color": "#FF0000"}, left={"sz": 12, "val": "single", "color": "#FF0000"}, right={"sz": 12, "val": "single", "color": "#FF0000"}, )

整体代码:

from docx import * from docx.oxml import OxmlElement from docx.oxml.ns import qn##qn#设置中文字体 #设置表格的边框 def set_cell_border(cell, **kwargs): """ Set cell`s border Usage: set_cell_border( cell, top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"}, bottom={"sz": 12, "color": "#00FF00", "val": "single"}, left={"sz": 24, "val": "dashed", "shadow": "true"}, right={"sz": 12, "val": "dashed"}, ) """ tc = cell._tc tcPr = tc.get_or_add_tcPr() # check for tag existnace, if none found, then create one tcBorders = tcPr.first_child_found_in("w:tcBorders") if tcBorders is None: tcBorders = OxmlElement('w:tcBorders') tcPr.append(tcBorders) # list over all available tags for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'): edge_data = kwargs.get(edge) if edge_data: tag = 'w:{}'.format(edge) # check for tag existnace, if none found, then create one element = tcBorders.find(qn(tag)) if element is None: element = OxmlElement(tag) tcBorders.append(element) # looks like order of attributes is important for key in ["sz", "val", "color", "space", "shadow"]: if key in edge_data: element.set(qn('w:{}'.format(key)), str(edge_data[key])) doc=Document() #设置默认字体 doc.styles['Normal'].font.name = u'宋体' doc.styles['Normal'].font.name = u'宋体' doc.styles['Normal'].font.name = 'Times New Roman' doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') table = doc.add_table(rows=8, cols=5) table.style ='Table Grid' hdr_cells = table.rows[0].cells hdr_cells[0].text = '编号编号' hdr_cells[1].text = '漏洞名称' hdr_cells[2].text = '影响IP' hdr_cells[3].text = 'CVE ID' hdr_cells[4].text = '危险程度' # #用table的row方法可以得到一个表格的一行list其中包含了这一行的所有cell # hdr_cells0 = table.rows[1].cells # hdr_cells0[0].add_paragraph('1') # hdr_cells0[2].add_paragraph('192.168.1.1') # hdr_cells0[3].add_paragraph('CVE-2019-0708') # hdr_cells0[4].add_paragraph('高') set_cell_border(hdr_cells[0], top={"sz": 12, "val": "single", "color": "#FF0000"}, bottom={"sz": 12, "val": "single", "color": "#FF0000"}, left={"sz": 12, "val": "single", "color": "#FF0000"}, right={"sz": 12, "val": "single", "color": "#FF0000"}, ) doc.save('table.docx')

运行结果: 在这里插入图片描述

三、向表格中添加数据

1、向表格中第二行添加数据

hdr_cells0 = table.rows[1].cells hdr_cells0[0].add_paragraph('1') hdr_cells0[1].add_paragraph('CVE-2019-0708 远程桌面代码执行漏洞') hdr_cells0[2].add_paragraph('192.168.1.1') hdr_cells0[3].add_paragraph('CVE-2019-0708') hdr_cells0[4].add_paragraph('高')

运行结果: 在这里插入图片描述 2、向指定单元格添加数据

cell = table.cell(1, 3) # 获取第二行三列的表格对象(索引是从0开始的) cell.text='向第二行第三列添加的文字'# 在单元格中添加文本:

运行结果: 在这里插入图片描述 四、设置表格对齐

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.enum.table import WD_TABLE_ALIGNMENT, WD_CELL_VERTICAL_ALIGNMENT table.alignment = WD_TABLE_ALIGNMENT.CENTER # 设置表格居中对齐 for column in table.columns: # 所有列 for cell in column.cells: # 所有单元格 for paragraph in cell.paragraphs: # 所有段落 paragraph.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # 水平对齐,居中

运行结果: 在这里插入图片描述 我公众号大家可以关注支持一哈 主要记录一些网络安全和Python的学习。 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3