python 读取excel内容写入到world中
根据sheet的数量生成对应的world文档
import xlrd
from docx import Document # 功能是打开文档
from docx.shared import Pt # 设置磅数
from docxtpl import DocxTemplate
from docx.enum.text import WD_ALIGN_PARAGRAPH # 功能是对齐
from docx.oxml.ns import qn # 负责中文格式 以上是每次使用word要使用的库
from docx.shared import Cm # 调整行高和列宽
document = Document() # 初始化文档
document.styles['Normal'].font.name = u'仿宋' # 设置整个文档的字体
document.styles['Normal'].font.size = Pt(12) # 设置文档磅号
document.styles['Normal'].element.rPr.rFonts.set(qn('w:esatAsia'), u'仿宋')
def read_excel():
# 打开excel表格
data_excel = xlrd.open_workbook('运营管理二期测试用例.xlsx')
# 获取所有sheet名称
names = data_excel.sheet_names()
for name in names:
# 根据sheet名称获取对应的表
table = data_excel.sheet_by_name(sheet_name='%s' % name)
# 获取sheet中总行数
n_rows = table.nrows
for row in range(1, n_rows):
check_point = table.row_values(row)[10]
transaction_name = table.row_values(row)[4]
test_procedure = table.row_values(row)[12]
test_procedure_list = test_procedure.split()
procedure_str = ''
for procedure in test_procedure_list:
procedure_str += procedure
expected_results = table.row_values(row)[13]
document.add_paragraph("%s.【案例】:%s" % (row, check_point.strip()))
document.add_paragraph("【交易/模块】:%s" % transaction_name.strip())
test_procedure.split()
document.add_paragraph("【步骤】:%s" % procedure_str)
document.add_paragraph("【结果】:%s" % expected_results.strip())
document.add_paragraph("【测试结论】:测试通过")
paragraph = document.add_paragraph("【测试截图】:")
paragraph_format = paragraph.paragraph_format
paragraph_format.space_after = Pt(80) # 上行间距
document.save("{}".format(name) + ".docx")
read_excel()