document.add_heading('The REAL meaning of the universe') #添加一级标题(在word里对应‘Heading 1’ document.add_heading('The role of dolphins', level=2) #添加小标题,可以包括1-9 document.add_heading('The role of dolphins', level=0) #添加title
row1 = table.rows[1] #第2行,每个table可以.rows,每个row可以.cells row.cells[0].text = 'Foo bar to you.'#第2行第一列 row.cells[1].text = 'And a hearty foo bar to you too sir!'
#遍历每一个cell for row in table.rows: for cell in row.cells: print(cell.text) #添加行 row = table.add_row()
# add a data row for each item for item in items: cells = table.add_row().cells cells[0].text = str(item.qty) cells[1].text = item.sku cells[2].text = item.desc #设置表格属性 from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.enum.table import WD_ALIGN_VERTICAL
#写入 for p in doc.paragraphs: print(p.text) if'XXX'in p.text: inline = p.runs for i in range(len(inline)): print(i) if'XXX'in inline[i].text: text = inline[i].text.replace('XXX', textlist[count]) inline[i].text = text count+=1 print(count) doc.save("%s_证明.docx"%name)
from docx import Document #准备写入内容 import xlrd import time # 当前时间元组 from datetime import datetime nt=datetime.now() # 可以输入中文年月日 datestr=nt.strftime('%Y{y}%m{m}%d{d}').format(y='年', m='月', d='日')
xlsx=xlrd.open_workbook('test.xlsx') sheet=xlsx.sheet_by_index(0) for row in range(1,sheet.nrows): doc = Document("证明.docx") count=0 textlist=[] for col in range(0,sheet.ncols): textlist.append(str(sheet.cell_value(row, col)))
for p in doc.paragraphs: if'XXX'in p.text: inline = p.runs for i in range(len(inline)): if'XXX'in inline[i].text: text = inline[i].text.replace('XXX', textlist[count]) inline[i].text = text count+=1 if'X 年 X 月 X 日'in p.text: inline = p.runs for i in range(len(inline)): if'X 年 X 月 X 日'in inline[i].text: text = inline[i].text.replace('X 年 X 月 X 日', datestr) inline[i].text = text