from docx import Document from docx.shared import Cm #引入cm单位,便于设置图片的宽度 from docx.enum.table import WD_TABLE_ALIGNMENT #用于设置单元格的内容居中对齐
document = Document() # 添加表格
tab1 =document.add_table(rows=1,cols=1) #添加一个1行1列的空表
cell=tab1.cell(0,0) #获取某单元格对象(从0开始索引) # 在单元格中添加段落,区块
c_p1 =cell.paragraphs[0]
c_p1.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER #设置单元格内容居中对齐 c_run1=c_p1.add_run() # 在单元格中添加图片,我的图片是bar.png,图片和py文件在同一个目录下
c_run1.add_picture('bar.png',width=Cm(10)) #保存.docx文档
document.save('demo.docx')
def save_docs_temp(self):
"""根据当前系统模板,自动生成word文档
# doc.add_picture("E:\\HD_Settled\\dtcloud360\\gz2.jpg")
"""
doc_path = self.env['ir.config_parameter'].get_param('docx_template_path')
doc = DocxTemplate(doc_path) # 模板文档
tab1 = doc.add_table(rows=1, cols=1)
cell = tab1.cell(0, 0)
c_p1 = cell.paragraphs[0]
c_run1 = c_p1.add_run()
c_run1.add_picture((io.BytesIO(base64.b64decode(self.image_1920)))),
context = {'name': self.name or '', 'sex': gender_dict[self.gender],
'age': self.age or '', 'nation': self.base_nation.name,
'birtd': self.date_birthday or '', 'company_name': self.company_id.name or '',
'work_data': self.participate_time or '', 'join_data': self.join_company_time or '',
'pol_outlook': pol_dict[self.pol_outlook], 'education': self.education or '',
'major_studied': self.major_studied or '',
'talent_level': self.talent_level or '', 'graduation_school': self.graduation_school or '',
'job_education': self.job_education or '', 'job_major': self.job_graduation_school or '',
'specific_specialty': self.specific_specialty or '', 'degree_education': self.degree_education or '',
'talent_professional_name': self.talent_professional_id.name or '',
'talent_skill_name': self.talent_skill_job_id.name or '',
'job_name': self.job_name or '', 'rank_level': self.rank_level or '',
# 'talent_secret': (io.BytesIO(base64.b64decode(self.image_1920))),
# 'talent_secret': doc.add_picture(('test.png', base64.b64decode(self.image_1920), 'image/png')),
'other_professional': self.other_professional or '',
'talent_title': self.talent_title or ''
} # 待替换对象
doc.render(context) # 执行替换
# 插入图片操作
# table.add_picture((io.BytesIO(base64.b64decode(self.image_1920)))),
buffer = BytesIO()
doc.save(buffer)
return base64.encodebytes(buffer.getvalue())
def btn_doc_method(self):
"""下载docx"""
context = dict(self._context or {})
active_ids = context.get('active_ids', []) or []
wiz_obj = self.env['talent.export.export.data.wizard']
filename = '人员信息表%s-%s' % (self.name, datetime.today().strftime('%Y-%m-%d'))
wiz_id = wiz_obj.sudo().create({
'file_data': self.save_docs_temp()
})
value = dict(
type='ir.actions.act_url',
target='self',
url='/web/content?model=%s&id=%s&field=file_data&download=true&filename=%s.docx' % (
'talent.export.export.data.wizard', wiz_id.id, filename),
)
return value