def document(): doc = Document() doc.add_heading('Fake Title', 0) doc.add_heading('Fake Header 1', 1) doc.add_heading('Fake Header 2', 2) # Redefine font parameters for 'Normal' style style = doc.styles['Normal'] font = style.font font.name = 'Calibri' font.size = Pt(12) # Add some text (paragraph) of 'Normal' style p = doc.add_paragraph('Some ') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True # Set custom paragraph attributes paragraph_format = p.paragraph_format paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY paragraph_format.left_indent = Cm(0.5) paragraph_format.right_indent = Cm(0.5) paragraph_format.space_before = Cm(1) paragraph_format.space_after = Cm(1) paragraph_format.first_line_indent = Cm(1.25) paragraph_format.line_spacing = Cm(1.0) paragraph_format.keep_with_next = True # Add new section doc.add_section() return doc
def buildDoc(table, tableData): doc = Document() #debug print('Loaded {}'.format(tableData)) for row in tableData: print('row {}'.format(row)) level = 'Heading ' + str(row['level'] + 1) title = str(row['logical_order'] or '') + " " + row['name'] if row['id'] == 0: doc.add_heading(title, 0) doc.add_section() doc.add_section() else: heading = doc.add_heading(title, row['level']) heading.style = doc.styles[level] p = doc.add_paragraph(row['description']) # https://stackoverflow.com/a/16859266/65706 #if row['img_relative_path']: # ip = document.add_paragraph() # r = p.add_run() # r.add_text(row['img_name']) # r.add_picture('/tmp/foo.jpg') if row['src']: src = doc.add_paragraph(row['src']) src.style = doc.styles['Body Text 3'] full_path = path + "/" + table.replace('_', '.').replace('doc', 'docx') doc.save(full_path) return 0
def processa(_col_pontos, _col_campanha, _col_parametro, _idleg, _idclasse): document = Document('/home/wbeirigo/Clima/weather/proj/matriz.docx') URL_PHANTOM = 'http://10.3.0.29:3003' headers ={ 'Content-Type': 'application/json', '-X POST':'' } indice = 0 section = document.add_section() section.orientation = WD_ORIENT.LANDSCAPE indice += 1 document.add_paragraph(' ', style='Normal') document.add_paragraph(' ', style='Normal') document.add_heading(u'Quadro 6.{0} - - Resultados do monitoramento da qualidade da água'.format(indice, ''), level=2) #geraTabela(document, _col_pontos, _col_campanha, _idleg, _idclasse) document.add_paragraph(' ', style='Normal') section = document.add_section() section.orientation = WD_ORIENT.PORTRAIT for parametro in _col_parametro: """ Não processa parametros Data e Profundidade""" if parametro in (798,840): continue saida = geraGraphico(_col_pontos, _col_campanha, parametro, _idleg, _idclasse) if not saida: continue r = requests.post(URL_PHANTOM, data=saida, headers=headers) png_recovered = base64.decodestring(r.content) path = "/tmp/{0}.png".format(int(time.time()*1000)) f = open(path, "w") f.write(png_recovered) f.close() indice += 1 obj_param = Param.objects.get(pk=parametro) nome = obj_param.nome texto = obj_param.texto document.add_heading(u'6.{0} - {1}'.format(indice, nome), level=3) document.add_paragraph(' ', style='Normal') document.add_paragraph(texto, style='Normal') document.add_paragraph(' ', style='Normal') document.add_paragraph(' ', style='Normal') document.add_paragraph(u'Figura 6.{0} -Resultados obtidos para o parâmetro {1}'.format(indice, nome), style='f') document.add_picture(path, width=Inches(5.2)) document.add_paragraph(' ', style='Normal') last_paragraph = document.paragraphs[-1] last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER document.add_page_break() os.remove(path) caminho = '/media/projeto_cemig/01_SOFTWARE/rel/' path = caminho + "{0}.docx".format(int(time.time()*1000)) document.save(path) return path
def create_and_format_document(title=""): doc = Document() p1 = doc.add_paragraph() p1.alignment = WD_ALIGN_PARAGRAPH.CENTER t1 = p1.add_run(title) t1.font.size = Pt(24) doc.add_section(WD_SECTION.CONTINUOUS) section = doc.sections[-1] sectPr = section._sectPr cols = sectPr.xpath('./w:cols')[0] cols.set(qn('w:num'), '2') return doc
def add_text(content): flag = 0 for i in Doc: if i["Name"] is content["name"]: DDoc = i["Docx"] flag = 1 if flag is 0: doc = Document() docs = {"Docx": doc, "Name": content["name"]} Doc.append(docs) DDoc = docs["Docx"] chg_doc(DDoc, content["name"]) section = doc.add_section() section._sectPr.xpath('./w:cols')[0].set(qn('w:num'), '2') #print(content) global cnt global totalCnt print(totalCnt) totalCnt += 1 paragraph = doc.add_paragraph() paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER run = paragraph.add_run(content['name']) addShadeToTxt(run) run.bold = True #设置字体为粗体 chg_font(run, fontname='微软雅黑', size=Pt(14)) #设置字体和字 for concreteContent in content['activity']: addShadeToTxt(run) run = paragraph.add_run(concreteContent[0]) chg_font(run, fontname='微软雅黑', size=Pt(11)) run = paragraph.add_run(concreteContent[1]) run.add_break() chg_font(run, fontname='微软雅黑', size=Pt(12)) images = concreteContent[2].split(',') for image in images: paragraph = doc.add_paragraph() paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER run = paragraph.add_run("") cnt += 1 if cnt % 2 == 0: imagename = str(cnt) + ".jpg" image = image.strip() if ".jpg" in image: #print(image) urllib.request.urlretrieve(image, filename=imagename) run.add_picture(imagename, width=Inches(4.25)) ph_format = paragraph.paragraph_format ph_format.space_before = Pt(10) #设置段前间距 ph_format.space_after = Pt(12) #设置段后间距 ph_format.line_spacing = Pt(19) #设置行间距
class WordUtils: def __init__(self, fileName): self._file = fileName self._doc = Document() # 设置默认字体 self._doc.styles['Normal'].font.name = '微软雅黑' self._doc.styles['Normal']._element.rPr.rFonts.set( qn('w:eastAsia'), '微软雅黑') # 添加段落 def _add_paragraph(self, content, style="ListBullet", bold=False): paragraph = self._doc.add_paragraph() run = paragraph.add_run(content) run.bold = bold return paragraph # 添加标题 def _add_heading(self, content, level=2): self._doc.add_heading(content, level) # 添加分页符 def _add_page_break(self): self._doc.add_page_break() # 添加表格 def _add_table(self, rows, cols, data=[[]], style="Table Grid"): table = self._doc.add_table(rows, cols) table.style = style for i in range(rows): for j in range(cols): table.cell(i, j).text = data[i][j] # 添加图片 def _add_picture(self, location, width=1): self._doc.add_picture(location, width=Inches(width)) # 添加章节 def _add_section(self): return self._doc.add_section(WD_SECTION.ODD_PAGE) # 保存文件 def _save(self): self._doc.save(self._file)
def convertDoc(self, unicodeFont, debugInfo=None): # Creating a new document newdoc = Document() # TODO: set up style with new Unicode font for style in self.doc_in.styles: newdoc.styles.add_style(style.name, style.type) new_paragraph = newdoc.add_paragraph() new_paragraph.style = style print('Added style %s' % style.name) self.deleteParagraph(new_paragraph) for old_section in self.doc_in.sections: new_section = newdoc.add_section(start_type=old_section.start_type) new_section.page_height = old_section.page_height new_section.page_width = old_section.page_width new_section.orientation = old_section.orientation new_section.top_margin = old_section.top_margin new_section.gutter = old_section.gutter new_section.header_distance = old_section.header_distance new_section.footer_distance = old_section.footer_distance new_section.left_margin = old_section.left_margin new_section.right_margin = old_section.right_margin hparagraph = new_section.header.paragraphs[0] hparagraph.text = old_section.header.paragraphs[0].text p_num = 0 for old_p in self.doc_in.paragraphs: if not old_p.text: print('P %d is empty' % p_num) p_num += 1 # Add simple text paragraph, converted as a whole # newText = self.converter.convertText(old_p.text) if self.converter else old_p.text new_p = newdoc.add_paragraph() # Copy properties of the paragraph new_p.style = old_p.style old_p_format = old_p.paragraph_format new_p_format = new_p.paragraph_format # new_p.paragraph_format = old_p.paragraph_format new_p_format.line_spacing_rule = old_p_format.line_spacing_rule new_p_format.alignment = old_p_format.alignment new_p_format.left_indent = old_p_format.left_indent new_p_format.right_indent = old_p_format.right_indent new_p_format.first_line_indent = old_p_format.first_line_indent # Now get the runs of text, with compatibilities print('RUNS %2d old %2d new', (len(old_p.runs), len(new_p.runs))) new_runs = self.extractRuns(old_p, new_p) # Convert each run for run in new_p.runs: new_text = self.converter.convertText(run.text) run.text = new_text run.font.name = self.unicode_font_out run.rtl = self.converter.isRtl() # Now consider special punctuation and capitalization # TODO # For testing after combining and converting. self.analyzeRuns(new_runs) # TODO: process capitalization and punctuation adjustments. newdoc.save(self.path_out)
class CreateWord: def __init__(self, config=None, export_tabs=None, bulk_export=None, crawl_yml: dict = None, descript_lang: dict = None): try: self.datum = '{:%d-%b-%Y}'.format(date.today()) self.maand_jaar = '{:%B-%Y}'.format(date.today()) try: self.url = config['url'] self.domain = config['domain'] self.template_file = config['word_template'] self.search_console_url = config['search_console_url'] except KeyError as e: raise Exception("Error getting config variables: {}".format(e)) self.start_path = os.path.dirname(os.path.realpath(__file__)) self.domain_folder = self.set_data_domain_path() self.frog_data_folder = self.get_frog_folder() self.graph_data_folder = self.get_graph_folder() self.config_folder = self.get_config_folder() self.export_tabs = export_tabs self.bulk_export = bulk_export self.crawl_yml = crawl_yml self.descript_lang = descript_lang self.ps = None self.frog_files = {} self.document_fields = None self.doc = None self.dp = None self.data = {} self.co_table_headers = None self.co_readydata = None self.template = None self.dimensions_data = None cf = readConfig() self.config = cf.config self.ps_api = self.config['google_page_speed_api'] self.template = self.get_doc_template() self.word_output_file = self.get_doc_word_output() self.get_frog_files() self.create_crawl_data() self.get_crawl_overview_data() self.get_google_search_console_data() self.ps_all_data = {} # self.crawl_data = self.get_crawl_data() self.prep_document() self.merge_document() self.write_document() except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logging.warning(str(e) + " | " + str(exc_type) + " | " + str(fname) + " | " + str(exc_tb.tb_lineno)) return def get_doc_template(self): if self.template_file is not None: return os.path.join(self.start_path, "word_templates", self.template_file) def get_doc_word_output(self): return os.path.join(self.start_path, "word_output", "{}-{}.docx".format(self.maand_jaar, self.domain)) def get_config_folder(self): return os.path.join(self.start_path, 'config') def set_data_domain_path(self): return os.path.join(self.start_path, "data", self.domain) def get_graph_folder(self): return os.path.join(self.domain_folder, 'graphs') def get_frog_folder(self): return os.path.join(self.domain_folder, 'crawl') def get_frog_files(self): try: for r, d, f in os.walk(self.frog_data_folder): for file in f: if '.csv' in file: self.frog_files[file] = os.path.join(r, file) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logging.warning(str(e) + " | " + str(exc_type) + " | " + str(fname) + " | " + str(exc_tb.tb_lineno)) def create_crawl_data(self): try: t = 0 try: if os.path.isfile(self.frog_files['crawl_overview.csv']): t = os.path.getmtime(self.frog_files['crawl_overview.csv']) except KeyError: t = 0 if int(t) + 86400 <= int(time()): print('Creating Screaming Frog crawl data') export_tabs = [] bulk_export = [] for e in self.export_tabs['export_tabs']: if e['active'] == 1: export_tabs.append(e['id']) for b in self.bulk_export['bulk_exports']: if b['active'] == 1: bulk_export.append(b['id']) s = Screaming(self.domain_folder, self.url, self.search_console_url, export_tabs, bulk_export) s.run_screamer() else: print('Using current Screaming Frog crawl data') except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logging.critical(str(e) + " | " + str(exc_type) + " | " + str(fname) + " | " + str(exc_tb.tb_lineno)) sys.exit() def get_crawl_overview_data(self): try: try: co = CrawlOverview( crawl_file=self.frog_files['crawl_overview.csv'], crawl_yml=self.crawl_yml) except KeyError as e: raise Exception("Error getting frog files key: {}".format(e)) self.co_table_headers = co.table_headers self.co_readydata = co.readydata except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logging.critical(str(e) + " | " + str(exc_type) + " | " + str(fname) + " | " + str(exc_tb.tb_lineno)) return {} def get_google_search_console_data(self): self.dimensions_data = "" if self.search_console_url is not None and self.search_console_url != "": dimension = ['device', 'query', 'country', 'page'] g = GoogleSearchConsole(self.search_console_url, self.domain, date.today(), -30, dimension, self.config_folder) self.dimensions_data = g.dimension_data def prep_document(self): self.doc = Document(self.template) self.dp = DocxPrep(self.doc) self.dp.set_document_styles() def merge_document(self): sc = 0 EerstePagina(self.doc, sc, self.domain) inleiding(self.doc, self.domain) toc(self.doc) # crawl overzicht AlgemeenOverzicht(doc=self.doc, config=self.config, co_readydata=self.co_readydata, co_table_headers=self.co_table_headers, descript_lang=self.descript_lang) # Doc Pagespeed overzicht DocxPageSpeed(self.doc, self.config, self.url, self.domain, 'mobile') DocxPageSpeed(self.doc, self.config, self.url, self.domain, 'desktop') if self.dimensions_data != "": # only use when we have data! DocxGoogleSearch(self.doc, self.dimensions_data, self.graph_data_folder) else: self.dp.empty_page('Google Search Console') self.change_orientation() CSV2Docx(self.config, self.doc, self.frog_data_folder, self.export_tabs, self.bulk_export) # self.legenda() def legenda(self): self.change_orientation() self.doc.add_heading("Legenda & Uitleg", level=2) self.doc.add_paragraph() for key, val in self.ps_all_data['lighthouseResult']['audits'].items(): self.doc.add_heading(val['title'], level=3) self.doc.add_paragraph(val['description']) self.doc.add_paragraph() self.doc.add_heading("Google Zoeken", level=3) self.doc.add_heading("Klikken (CLicks)", level=4) self.doc.add_paragraph("Het aantal klikken (clicks) afkomstig van een Google zoekresultaat waarmee de " "gebruiker/bezoeker op je site is terechtgekomen.") self.doc.add_heading("Vertoningen", level=4) self.doc.add_paragraph( "Hoeveel links naar je site een gebruiker zag op de pagina met Google zoekresultaten van " "Google Zoeken. Vertoningen worden geteld wanneer de gebruiker die pagina met " "resultaten bezoekt, zelfs wanneer de gebruiker niet naar het resultaat is gescrold. " "Als een gebruiker echter alleen pagina 1 bekijkt en het resultaat op pagina 2 staat, " "telt die vertoning niet mee.") self.doc.add_heading("Positie", level=4) self.doc.add_paragraph("De gemiddelde positie van het hoogste resultaat van de site. " "Als je site bijvoorbeeld drie resultaten heeft op posities 2, 4 en 6, wordt de " "positie gerapporteerd als 2. Belangrijk is dat deze waarde zo laag mogelijk is, " "hoe lager hoe hoger in de zoek resultaten.") def change_orientation(self): current_section = self.doc.sections[-1] new_width, new_height = current_section.page_height, current_section.page_width new_section = self.doc.add_section(WD_SECTION.NEW_PAGE) new_section.orientation = WD_ORIENT.LANDSCAPE new_section.page_width = new_width new_section.page_height = new_height return new_section def set_repeat_table_header(self, row): """ set repeat table row on every new page """ tr = row._tr trPr = tr.get_or_add_trPr() tblHeader = OxmlElement('w:tblHeader') tblHeader.set(qn('w:val'), "true") trPr.append(tblHeader) return row def shade_cells(self, cells, shade): for cell in cells: tcPr = cell._tc.get_or_add_tcPr() tcVAlign = OxmlElement("w:shd") tcVAlign.set(qn("w:fill"), shade) tcPr.append(tcVAlign) def write_document(self): self.doc.save(self.word_output_file)
t.cell(0, 0).text = u'单元1' t.cell(0, 1).text = u'单元2' t.cell(1, 0).text = u'单元3' t.cell(1, 1).text = u'单元4' t = document.add_table(rows=2, cols=2) merge_cell = t.cell(0, 0).merge(t.cell(0, 1)) merge_cell.text = u'合并单元格' t = document.add_table(rows=2, cols=2) t.style = 'Table Grid' document.add_picture("./media/logo_for_1.png") img_url = "http://zeromq.wdfiles.com/local--files/admin:css/logo.gif" image_from_url = urllib2.urlopen(img_url) io_url = StringIO.StringIO() io_url.write(image_from_url.read()) io_url.seek(0) document.add_picture(io_url) # print "console------" # print len(document.styles) # for s in document.styles: # print s.name new_section = document.add_section(WD_SECTION.ODD_PAGE) document.save('./store/foo.docx')
# 使用Python操作Word from docx import Document from docx.shared import Inches # 空白文档 document = Document() #document = Document('./test.docx') #打开原有文档 paragraph = document.add_paragraph('基于Python的办公自动化处理') paragraph = document.add_paragraph('段落1:Word自动化') document.add_section() #添加新章节 paragraph = document.add_paragraph('章节2-1') document.add_section() #添加新章节 paragraph = document.add_paragraph('章节3-1') sections = document.sections #返回所有章节引用的对象 print('章节数=', len(sections)) #返回章节总数 # 得到指定section section = sections[0] #返回指定章节的对象 section = document.sections[-1] # 返回文档最后一个章节 # 得到section的信息,1英寸=914400像素 new_height = section.page_height new_width = section.page_width print('Section页面高={}, Section页面宽={}'.format(new_height, new_width)) print('左边距={}, 右边距={}, 上边距={}, 下边距={}'.format(section.left_margin, section.right_margin, section.top_margin, section.bottom_margin)) print('页眉距离={}, 页脚距离={}'.format(section.header_distance,
class Docx(object): """ Docx生成类 """ PAGE_HORIZONTAL = WD_ORIENT.LANDSCAPE PAGE_VERTICAL = WD_ORIENT.PORTRAIT def __init__(self): self._doc = Document() @staticmethod def CreateStyle(fontSize=14, fontName=u'宋体', bold=False, italic=False, underline=False, color=(0, 0, 0), align=Style.STYLE_ALIGN_LEFT): """ 创建样式 @param fontSize:字号 @param fontName:字体 @param bold:是否粗体 @param italic:是否斜体 @param underline:是否下划线 @param color:颜色 @param align:对齐方式,具体值参照Style类中的定义 @return:创建的样式 """ return Style(fontSize, fontName, bold, italic, underline, color, align) def AddHeader(self, level, text, style=None): """ 添加段落 @param style:样式 """ self._doc.add_paragraph("", self._doc.styles['heading %d' % level]) self.AddText(text, style) def AddParagraph(self, style=None): """ 添加段落 @param style:样式 """ paragraph = self._doc.add_paragraph() if style: paragraph.paragraph_format.alignment = style.align def AddText(self, text='', style=None, pid=-1): """ 添加文字 @param text:文字 @param style:样式 """ p = self._doc.paragraphs[pid] run = p.add_run(text) if style: run.font.size = style.fontSize run.font.name = style.fontName run.font.color.rgb = style.color run.italic = style.italic run.underline = style.underline run.bold = style.bold r = run._element r.rPr.rFonts.set(qn('w:eastAsia'), style.fontName) def AddPicture(self, picPath, width, dpi, caption, style): """ 添加图片 @param picPath:图片路径 @param width:图片宽度,设置了图片宽度后,高度根据图片大小自适应 @param caption:题注 @param style:样式 """ paragraph = self._doc.add_paragraph() paragraph.add_run().add_picture(picPath, width=Inches( float(width) / float(dpi))) paragraph.paragraph_format.alignment = style.align paragraph.paragraph_format.space_after = 0 self.AddParagraph(style) self.AddText(caption, style) def AddTable(self, rows, cols, caption, style=None): """ 添加表格 @param rows:行数 @param cols:列数 @param caption:题注 @param style:样式 """ paragraph = self._doc.add_paragraph() if style: paragraph.paragraph_format.alignment = style.align paragraph.paragraph_format.space_after = 0 self.AddText(caption, style) self._doc.add_table(rows=rows, cols=cols, style=self._doc.styles['Table Grid']) def SetCell(self, row, col, text, style=None, tid=-1): """ 设置单元格内容 @param tId:表格ID @param row:行数 @param col:列数 @param text:文字 @param style:样式 """ paragraph = self._doc.tables[tid].rows[row].cells[col].paragraphs[0] run = paragraph.add_run(text) if style: paragraph.paragraph_format.alignment = style.align run.font.size = style.fontSize run.font.name = style.fontName run.font.color.rgb = style.color run.italic = style.italic run.underline = style.underline run.bold = style.bold r = run._element r.rPr.rFonts.set(qn('w:eastAsia'), style.fontName) def AddPageBreak(self): """ 添加分页符 """ self._doc.add_page_break() def AddSection(self, orientation): section = self._doc.add_section(WD_SECTION.NEW_PAGE) section.orientation = orientation new_width, new_height = section.page_height, section.page_width section.page_width = new_width section.page_height = new_height def Save(self, docPath): """ 保存文档 @param docPath:保存路径 """ self._doc.save(docPath)
def create_page(text_chunk, vocabulary_list=None, doc=None, save=False, title=''): """Creates page of text and vocabulary. :param text_chunk: chunk of text to add to page """ chunk_dict = {} br = line_break if doc == None: doc = Document() main_paragraph = doc.add_paragraph().add_run(text_chunk) main_paragraph.font.size = Pt(12) # visual line break p2 = doc.add_paragraph() p2.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER p2.add_run(br) # column format doc.add_section(0) section = doc.sections[-1] sectPr = section._sectPr cols = sectPr.xpath('./w:cols')[0] cols.set(qn('w:num'), '2') # add words words = [ w.replace('\n', ' ').replace('—', ' ').strip('.,;:-—"').lower() for w in str(text_chunk).replace('\n', ' ').replace('—', ' ').split(' ') ] words = [w.strip(' !,.;:"-—') for w in words] for word in set(words): chunk_dict[word] = {} # parse the nominative form. works better than the OW parser if word == '': continue else: lemma = lemmatizer.lemmatize([word.lower()])[0][1] if lemma in vocabulary_list: # print(f'looking up {lemma}...') forms = lookup_word([lemma]).get(lemma) chunk_dict[word]['lemma'] = lemma chunk_dict[word]['dictionary_form'] = '' if forms.get('dictionary_form') is None\ else forms.get('dictionary_form') chunk_dict[word]['senses'] = '' if forms.get('senses') is None\ else forms.get('senses') # clean dictionary delete = [ k for k in chunk_dict.keys() if chunk_dict[k].get('dictionary_form') == '' ] for k in delete: del chunk_dict[k] chunk_vocab = sorted(list(chunk_dict.keys())) print(f"looked up {len(chunk_vocab)} words") if '' in chunk_vocab: chunk_vocab.remove('') # look up, format words for vocab_word in chunk_vocab: if chunk_dict[vocab_word] == {}: pass else: p = doc.add_paragraph() bold_text = f'{chunk_dict[vocab_word]["lemma"]} {" ".join(chunk_dict[vocab_word]["dictionary_form"]).strip(".")}: ' plain_text = f'{chunk_dict[vocab_word]["senses"]}' bold_run = p.add_run() bold_run.bold = True bold_run.text = bold_text bold_run.font.size = Pt(10) plain_run = p.add_run() plain_run.bold = False plain_run.text = plain_text plain_run.font.size = Pt(10) p.paragraph_format.space_after = Pt(0) doc.add_section(0) section = doc.sections[-1] # reset formatting sectPr = section._sectPr cols = sectPr.xpath('./w:cols')[0] cols.set(qn('w:num'), '1') doc.add_page_break() sections = doc.sections for section in sections: section.top_margin = Inches(0.5) section.bottom_margin = Inches(0.5) section.left_margin = Inches(.5) section.right_margin = Inches(.5) if save == True: doc.save(f'{title} with facing vocab.docx')
# 针对不同的项目绘制百分位线,按照顺序生成图片 date_list_dat = b.get_observe_days(b.o_d) birth_two_date_str = [] # 0-2岁的字符串日期 birth_two_len_h = [] # 0-2岁的身长 birth_two_weight = [] # 0-2岁的体重 two_five_date_str = [] # 2-5岁的字符串日期 two_five_len_h = [] # 2-5岁的身高 two_five_weight = [] # 2-5岁的体重 len_h_doc = [] len_doc_b_t = [] h_doc_t_f = [] weight_doc = [] se = document.add_section() se.left_margin = Inches(0) se.right_margin = Inches(0) for item in ['lhfa', 'wfa', 'hcfa', 'bfa', 'wfl', 'wfh']: if item == 'lhfa': # 身长、身高 # 需要区分年龄段 for str_d, day_d, len_hei, wei in zip(b.o_d, date_list_dat, b.o_l, b.o_w): if day_d <= 730: # 0-2岁的 birth_two_date_str.append(str_d) birth_two_len_h.append(len_hei) birth_two_weight.append(wei) else: # 2-5岁的 two_five_date_str.append(str_d) two_five_len_h.append(len_hei)
def saveDocx(parsedList, file): document = Document() document.sections[-1].left_margin = Pt(64) document.sections[-1].right_margin = Pt(64) document.sections[-1].top_margin = Cm(1.4) document.sections[-1].bottom_margin = Cm(1.4) normalStype = document.styles['Normal'] normalStype.font.name = 'Courier New' normalStype.font.size = Pt(10) #document.add_heading('Document Title', 0) lineIndex = 0 for e in parsedList: lineIndex += 1 p = document.add_paragraph('') p.style = normalStype p.paragraph_format.space_before = 0 p.paragraph_format.space_after = 0 p.paragraph_format.line_spacing = Pt(11) p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.EXACTLY ppr = p._element.get_or_add_pPr() w_nsmap = '{'+ppr.nsmap['w']+'}' bidi = None jc = None cs = None for element in ppr: if element.tag == w_nsmap + 'bidi': bidi = element if bidi is None: bidi = OxmlElement('w:bidi') bidi.set(qn('w:val'),'he-IL') ppr.append(bidi) for run in e: runText = run['text'] if runText.startswith('-') and runText.endswith('-') and runText[1:-1].isnumeric(): footer = document.sections[-1].footer footer.is_linked_to_previous = False fp = footer.paragraphs[0] fp.add_run(runText) fp.alignment = WD_ALIGN_PARAGRAPH.CENTER document.add_section() else: runText = runText + '\u200F' r = p.add_run(runText) if lineIndex > 60 and len(document.sections)<2: document.add_section() r.cs_size = Pt(10) r.cs_bold = run['bold'] r.bold = run['bold'] r.underline = run['underline'] if run['centered']: p.alignment = WD_ALIGN_PARAGRAPH.CENTER if run['left']: p.alignment = WD_ALIGN_PARAGRAPH.RIGHT ppr = r._element.get_or_add_rPr() w_nsmap = '{'+ppr.nsmap['w']+'}' bidi = None for element in ppr: if element.tag == w_nsmap + 'bidi': bidi = element if bidi is None: bidi = OxmlElement('w:bidi') bidi.set(qn('w:val'),'he-IL') ppr.append(bidi) ''' p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True document.add_heading('Heading, level 1', level=1) document.add_paragraph('Intense quote', style='Intense Quote') document.add_paragraph( 'first item in unordered list', style='List Bullet' ) document.add_paragraph( 'first item in ordered list', style='List Number' ) #document.add_picture('monty-truth.png', width=Inches(1.25)) records = ( (3, '101', 'Spam'), (7, '422', 'Eggs'), (4, '631', 'Spam, spam, eggs, and spam') ) table = document.add_table(rows=1, cols=3) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Qty' hdr_cells[1].text = 'Id' hdr_cells[2].text = 'Desc' for qty, id, desc in records: row_cells = table.add_row().cells row_cells[0].text = str(qty) row_cells[1].text = id row_cells[2].text = desc document.add_page_break() ''' document.save('out/demo-'+ os.path.split(file)[-1] +'.docx')
def auditReport(context): companyName = context["report_params"]["companyName"] companyAbbrName = context["report_params"]["CompanyAbbrName"] reportNo = context["report_params"]["reportNo"] reportType = context["report_params"]["type"] reportDate = context["report_params"]["reportDate"] reportPeriod = context["report_params"]["reportPeriod"] accountFirms = getAccountFirmNames(context["report_params"]["accountFirm"]) appellation = getAppellation(companyName) document = Document() # 设置中文标题 setStyle(document) document.add_paragraph() document.add_paragraph() title = document.add_paragraph() title.add_run('审计报告', style="title") title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER report_no = document.add_paragraph() report_no.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT report_no.add_run(reportNo, style="zero") document.add_paragraph() appellationPara = document.add_paragraph() appellationPara.add_run(appellation, style="first") document.add_paragraph() paragraph1 = document.add_paragraph(style="paragraphAfterSpace") paragraph1.add_run("一、审计意见", style="first") if reportType == "单体": audit_fan = [ "我们审计了", companyName, "(以下简称“", companyAbbrName, "”)财务报表,包括", reportDate, "的资产负债表,", reportPeriod, "的利润表、现金流量表、所有者权益变动表,以及相关财务报表附注。" ] else: audit_fan = [ "我们审计了", companyName, "(以下简称“", companyAbbrName, "”)财务报表,包括", reportDate, "的合并及母公司资产负债表,", reportPeriod, "的合并及母公司利润表、合并及母公司现金流量表、合并及母公司所有者权益变动表,以及相关财务报表附注。" ] paragraph2 = document.add_paragraph(style="paragraphAfterSpace") paragraph2.add_run("".join(audit_fan), style="zero") if reportType == "单体": audit_opinion = [ "我们认为,后附的财务报表在所有重大方面按照企业会计准则的规定编制,公允反映了", companyAbbrName, reportDate, "的财务状况以及", reportPeriod, "的经营成果和现金流量。" ] else: audit_opinion = [ "我们认为,后附的财务报表在所有重大方面按照企业会计准则的规定编制,公允反映了", companyAbbrName, reportDate, "的合并及母公司财务状况以及", reportPeriod, "的合并及母公司经营成果和现金流量。" ] paragraph3 = document.add_paragraph(style="paragraphAfterSpace") paragraph3.add_run("".join(audit_opinion), style="zero") document.add_paragraph() paragraph4 = document.add_paragraph(style="paragraphAfterSpace") paragraph4.add_run("二、形成审计意见的基础", style="first") audit_basic = [ "我们按照中国注册会计师审计准则的规定执行了审计工作。审计报告的“注册会计师对财务报表审计的责任”部分进一步阐述了我们在这些准则下的责任。按照中国注册会计师职业道德守则,我们独立于", companyAbbrName, ",并履行了职业道德方面的其他责任。我们相信,我们获取的审计证据是充分、适当的,为发表审计意见提供了基础。" ] paragraph5 = document.add_paragraph(style="paragraphAfterSpace") paragraph5.add_run("".join(audit_basic), style="zero") document.add_paragraph() # 是否添加关键审计事项 if len(context["report_params"]["keyAuditMatters"]) == 0: # 是否添加其他信息 if context["report_params"]["otherInfo"]: paragraph4 = document.add_paragraph(style="paragraphAfterSpace") paragraph4.add_run("三、其他信息", style="first") addOtherInfo(document, context) document.add_paragraph() paragraph6 = document.add_paragraph(style="paragraphAfterSpace") paragraph6.add_run("四、管理层和治理层对财务报表的责任", style="first") addManagementResponsebility(document, context) document.add_paragraph() paragraph10 = document.add_paragraph(style="paragraphAfterSpace") paragraph10.add_run("五、注册会计师对财务报表审计的责任", style="first") addCpaResponsibility(document, context) else: paragraph6 = document.add_paragraph(style="paragraphAfterSpace") paragraph6.add_run("三、管理层和治理层对财务报表的责任", style="first") addManagementResponsebility(document, context) document.add_paragraph() paragraph10 = document.add_paragraph(style="paragraphAfterSpace") paragraph10.add_run("四、注册会计师对财务报表审计的责任", style="first") addCpaResponsibility(document, context) else: # 披露关键审计事项 paragraph4 = document.add_paragraph(style="paragraphAfterSpace") paragraph4.add_run("三、关键审计事项", style="first") paragraph5 = document.add_paragraph(style="paragraphAfterSpace") paragraph5.add_run( "关键审计事项是我们根据职业判断,认为对本期财务报表审计最为重要的事项。这些事项的应对以对财务报表整体进行审计并形成审计意见为背景,我们不对这些事项单独发表意见。", style="zero") for key, item in enumerate( context["report_params"]["keyAuditMatters"]): paragraph5 = document.add_paragraph(style="paragraphAfterSpace") paragraph5.add_run(item["title"], style="zero") paragraph5 = document.add_paragraph(style="paragraphAfterSpace") paragraph5.add_run("1. 事项描述", style="zero") for desc in item["desc"]: paragraph5 = document.add_paragraph( style="paragraphAfterSpace") paragraph5.add_run(desc, style="zero") paragraph5 = document.add_paragraph(style="paragraphAfterSpace") paragraph5.add_run("2. 审计应对", style="zero") for response in item["auditResponse"]: paragraph5 = document.add_paragraph( style="paragraphAfterSpace") paragraph5.add_run(response, style="zero") # 是否添加其他信息 if context["report_params"]["otherInfo"]: document.add_paragraph() paragraph4 = document.add_paragraph(style="paragraphAfterSpace") paragraph4.add_run("四、其他信息", style="first") addOtherInfo(document, context) document.add_paragraph() paragraph6 = document.add_paragraph(style="paragraphAfterSpace") paragraph6.add_run("五、管理层和治理层对财务报表的责任", style="first") addManagementResponsebility(document, context) document.add_paragraph() paragraph10 = document.add_paragraph(style="paragraphAfterSpace") paragraph10.add_run("六、注册会计师对财务报表审计的责任", style="first") addCpaResponsibility(document, context) else: document.add_paragraph() paragraph6 = document.add_paragraph(style="paragraphAfterSpace") paragraph6.add_run("四、管理层和治理层对财务报表的责任", style="first") addManagementResponsebility(document, context) document.add_paragraph() paragraph10 = document.add_paragraph(style="paragraphAfterSpace") paragraph10.add_run("五、注册会计师对财务报表审计的责任", style="first") addCpaResponsibility(document, context) document.add_paragraph() document.add_paragraph() document.add_paragraph() document.add_paragraph() document.add_paragraph() document.add_paragraph() table = document.add_table(rows=3, cols=2) cell00 = table.cell(0, 0).add_paragraph() cell00.add_run(accountFirms[0], style="zero") cell00.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER if len(accountFirms) > 1: cell00 = table.cell(0, 0).add_paragraph() cell00.add_run(accountFirms[1], style="zero") cell00.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cell01 = table.cell(0, 1).add_paragraph() cell01.add_run("中国注册会计师:", style="zero") cell00 = table.cell(1, 0).add_paragraph() cell00.add_run(context["report_params"]["accountFirmAddr"], style="zero") cell00.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER cell11 = table.cell(1, 1).add_paragraph() cell11.add_run("中国注册会计师:", style="zero") cell21 = table.cell(2, 1).add_paragraph() cell21.add_run(context["report_params"]["issuanceDate"], style="zero") document.add_section() # 给报告添加页码 add_page_number(document.sections[0].footer.paragraphs[0]) return document
return result, img if __name__ == '__main__': from docx import Document from docx.oxml.ns import qn doc = Document() doc.styles['Normal'].font.name = u'宋体' doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体') pdf_path = r'F:\数据\txt_pdfs\16550822.pdf' start_page, end_page = 0, 1 for page in range(start_page, end_page): # pdf_pages(pdf_path) print(page) print(pdf_is_text(pdf_path)) result, img = extract_pdf_text(pdf_path, page) print(result) doc = save2docx(doc, result, img, page) if page == end_page - 1: continue doc.add_section() doc.save('aaa2.docx') # for i in os.listdir(r'F:\数据\txt_pdfs'): # if not pdf_is_text(r'F:\数据\txt_pdfs/' + i): # print(i) # print(pdf_is_text(pdf_path))
# 将.docx版的文档转变为pdf格式 from docx import Document from docx.shared import Inches, RGBColor from docx.oxml.ns import qn from docx.shared import Pt import docx.enum.text as s import baby_grow_report as g_report from win32com import client # docx转化为pdf add_docu = Document(r'%s\%s_report.docx' % (g_report.b.path_name, g_report.b.b_n)) se = add_docu.add_section() se.left_margin = Inches(0.4) se.right_margin = Inches(0.4) # 添加第七节 # 如何操作 t8 = add_docu.add_heading('', 0).add_run(g_report.contents_lsit[6]) t8.font.size = Pt(25) # 字体大小 t8.bold = True # 字体是否加粗 t8.font.name = 'Times New Roman' # 控制是西文时的字体 t8.element.rPr.rFonts.set(qn('w:eastAsia'), '黑体') p = add_docu.add_paragraph('') p.paragraph_format.alignment = s.WD_ALIGN_PARAGRAPH.CENTER t8.font.color.rgb = RGBColor(*g_report.color) step1 = add_docu.add_paragraph('')
def build_document(scenario): ''' id = scenario id ''' try: theme = scenario.theme structure = get_object_or_404(Structure, theme=theme) style = get_object_or_404(Style, theme=theme) # all_platforms = full list of platforms. excludes alternative if selected all_platforms = get_platforms(get_list_or_404(Platform, scenario=scenario), structure) all_platforms = get_consolidated_balance(all_platforms) asset_allocation = get_aa(all_platforms, scenario) investments = get_list_or_404(Investment, platform__scenario=scenario) # platform_slice = reduced list after splitting platform_slices = [all_platforms] document = Document() # tables = ["aa", "actual", "consolidated"] IMPROT THIS FROM MODEL table_types = Content.TABLE_TYPE_CHOICES # If there are no recommended platforms, remove consolidated table. if not next((p for p in all_platforms if p.status == "Recommended"), False): table_types = [t for t in table_types if t[0] != "Consolidated"] # Build style sets build_element_style_set(document, style) table_style = build_table_style_set(document, style) #Set sections for first page section = document.sections[0] prev_section = 0 if structure.split_platform_types: platform_slices = split_platform_types(platform_slices) for table_type in [i[0] for i in table_types]: content = theme.content.filter(table_type=table_type, visible=True) if (table_type == "AA"): orientation = get_orientation(0, structure) set_orientation(section, prev_section, orientation) build_aa_tables(document, style, table_style, structure, content, asset_allocation) prev_section = section section = document.add_section(WD_SECTION.NEW_PAGE) elif (table_type == "Consolidated") or (table_type == "Actual") or (table_type == "Product"): if table_type == "Consolidated": all_platforms = get_consolidated_data(all_platforms) for platform_slice in platform_slices: # Want to split super/inv here and iterate on platform groupings num_table_splits = get_num_table_splits(all_platforms, structure) if (table_type == "Consolidated") or (table_type == "Actual"): orientation = get_orientation(num_table_splits, structure) set_orientation(section, prev_section, orientation) build_fee_tables(all_platforms, structure, table_type, document, style, table_style, content, platform_slice, num_table_splits, orientation) elif table_type == "Product": orientation = get_orientation(0, structure) set_orientation(section, prev_section, orientation) build_product_tables(document, style, table_style, structure, content, platform_slice, investments) prev_section = section section = document.add_section(WD_SECTION.NEW_PAGE) return save_document(document, scenario) except Exception as e: print(e) print (traceback.format_exc())
def exportWord(): isJsonFinish = exportJson() if isJsonFinish == False: return isJsonFinish # JsonDict = json.loads(open('test.json').read()) doc = Document() font_HeiTi = u'黑体' font_SongTi = u'宋体' font_FangSong = u'仿宋_GB2312' # 标题字体 style = doc.styles['Caption'] style.font.bold = True style.font.size = Pt(26) # 段落标题字体 style = doc.styles['Normal'] style.font.bold = True style.font.size = Pt(14) # 段落标题括号内容字体 style = doc.styles['Body Text 3'] style.font.bold = False style.font.size = Pt(14) # 填写内容字体 style = doc.styles['Body Text'] # paragraph style.font.bold = False style.font.size = Pt(12) style = doc.styles['Body Text Char'] # character style.font.bold = False style.font.size = Pt(12) # 段落中的注释字体 style = doc.styles['Body Text 2'] style.font.bold = False style.font.size = Pt(10) ''' 封面 ''' title = u'国防科技卓越青年人才基金\n项目申报书' doc.add_paragraph('\n\n') paraTitle = doc.add_paragraph() paraRun = paraTitle.add_run(title) setFont(paraRun, 26, True, font_HeiTi) doc.add_paragraph('\n' * 4) paraTitle.alignment = WD_ALIGN_PARAGRAPH.CENTER label1 = u'\t\t\t申报类型: ' label2 = u'\t\t\t申 请 人: ' label3 = u'\t\t\t项目名称: ' label4 = u'\t\t\t申报领域: ' label5 = u'\t\t\t工作单位: ' label6 = u'\t\t\t联系电话: ' type = doc.add_paragraph() typeTitleRun = type.add_run(label1) setFont(typeTitleRun, 16, True, font_HeiTi) typeRun = type.add_run(text=JsonDict['cover']['type']) setFont(typeRun, 16, False, font_SongTi) applicant = doc.add_paragraph() applicantTitleRun = applicant.add_run(label2) setFont(applicantTitleRun, 16, True, font_HeiTi) applicantRun = applicant.add_run(JsonDict['cover']['applicant']) setFont(applicantRun, 16, False, font_SongTi) project_name = doc.add_paragraph() project_nameTitleRun = project_name.add_run(label3) setFont(project_nameTitleRun, 16, True, font_HeiTi) project_nameRun = project_name.add_run(JsonDict['cover']['project_name']) setFont(project_nameRun, 16, False, font_SongTi) application_field = doc.add_paragraph() application_fieldTitleRun = application_field.add_run(label4) setFont(application_fieldTitleRun, 16, True, font_HeiTi) application_fieldRun = application_field.add_run( JsonDict['cover']['application_field']) setFont(application_fieldRun, 16, False, font_SongTi) working_dep = doc.add_paragraph() working_depTitleRun = working_dep.add_run(label5) setFont(working_depTitleRun, 16, True, font_HeiTi) working_depRun = working_dep.add_run(JsonDict['cover']['working_dep']) setFont(working_depRun, 16, False, font_SongTi) telephone = doc.add_paragraph() telephoneTitleRun = telephone.add_run(label6) setFont(telephoneTitleRun, 16, True, font_HeiTi) telephoneRun = telephone.add_run(JsonDict['cover']['telephone']) setFont(telephoneRun, 16, False, font_SongTi) bottom = doc.add_paragraph('\n' * 7) zyjw = bottom.add_run(u'中央军委科学技术委员会制\n') setFont(zyjw, 14, False, font_SongTi) finishDate = bottom.add_run(u'二〇一七年%s月%s日' % (' ' * 4, ' ' * 4)) setFont(finishDate, 14, False, font_SongTi) bottom.alignment = WD_ALIGN_PARAGRAPH.CENTER doc.add_section(start_type=1) ''' 一、申请人基本信息 ''' baseInfo_title = doc.add_paragraph() baseInfo_titleRun = baseInfo_title.add_run(u'一、申请人基本信息') setFont(baseInfo_titleRun, 16, True, font_HeiTi) baseInfo = doc.add_table(rows=8, cols=7, style='Table Grid') # baseInfo.cell(2, 0).text = u'申请人情况' setInitCell(baseInfo.cell(2, 0), u'申请人情况', bold=True) baseInfo.cell(0, 0).merge(baseInfo.cell(1, 0)).merge(baseInfo.cell( 2, 0)).merge(baseInfo.cell(3, 0)).merge(baseInfo.cell(4, 0)) # baseInfo.cell(0, 1).text = u'姓 名' # baseInfo.cell(0, 2).text = JsonDict['basic_info']['personal_info']['name'] # baseInfo.cell(0, 3).text = u'性 别' # baseInfo.cell(0, 4).text = JsonDict['basic_info']['personal_info']['gender'] # baseInfo.cell(0, 5).text = u'出生年月' # baseInfo.cell(0, 6).text = JsonDict['basic_info']['personal_info']['birthday'] setInitCell(baseInfo.cell(0, 1), u'姓 名') setEditCell(baseInfo.cell(0, 2), JsonDict['basic_info']['personal_info']['name']) setInitCell(baseInfo.cell(0, 3), u'性 别') setEditCell(baseInfo.cell(0, 4), JsonDict['basic_info']['personal_info']['gender']) setInitCell(baseInfo.cell(0, 5), u'出生年月') setEditCell(baseInfo.cell(0, 6), JsonDict['basic_info']['personal_info']['birthday']) # baseInfo.cell(1, 1).text = u'学 位' # baseInfo.cell(1, 2).text = JsonDict['basic_info']['personal_info']['bachelor'] # baseInfo.cell(1, 3).text = u'职 称' # baseInfo.cell(1, 4).text = JsonDict['basic_info']['personal_info']['job'] # baseInfo.cell(1, 5).text = u'单位职务' # baseInfo.cell(1, 6).text = JsonDict['basic_info']['personal_info']['dep_job'] setInitCell(baseInfo.cell(1, 1), u'学 位') setEditCell(baseInfo.cell(1, 2), JsonDict['basic_info']['personal_info']['bachelor']) setInitCell(baseInfo.cell(1, 3), u'职 称') setEditCell(baseInfo.cell(1, 4), JsonDict['basic_info']['personal_info']['job']) setInitCell(baseInfo.cell(1, 5), u'单位职务') setEditCell(baseInfo.cell(1, 6), JsonDict['basic_info']['personal_info']['dep_job']) # baseInfo.cell(2, 1).text = u'主要研究方向' # baseInfo.cell(2, 2).text = JsonDict['basic_info']['personal_info']['research'] setInitCell(baseInfo.cell(2, 1), u'主要研究方向') setEditCell(baseInfo.cell(2, 2), JsonDict['basic_info']['personal_info']['research']) baseInfo.cell(2, 2).merge(baseInfo.cell(2, 3)).merge(baseInfo.cell( 2, 4)).merge(baseInfo.cell(2, 5)).merge(baseInfo.cell(2, 6)) # baseInfo.cell(3, 1).text = u'身份证件名称' # baseInfo.cell(3, 2).text = JsonDict['basic_info']['personal_info']['id_name'] # baseInfo.cell(3, 3).text = u'证件编号' # baseInfo.cell(3, 4).text = JsonDict['basic_info']['personal_info']['id_num'] setInitCell(baseInfo.cell(3, 1), u'身份证件名称') setEditCell(baseInfo.cell(3, 2), JsonDict['basic_info']['personal_info']['id_name']) setInitCell(baseInfo.cell(3, 3), u'证件编号') setEditCell(baseInfo.cell(3, 4), JsonDict['basic_info']['personal_info']['id_num']) baseInfo.cell(3, 4).merge(baseInfo.cell(3, 5)).merge(baseInfo.cell(3, 6)) # baseInfo.cell(4, 1).text = u'办公电话' # baseInfo.cell(4, 2).text = JsonDict['basic_info']['personal_info']['office_phone'] # baseInfo.cell(4, 3).text = u'手 机' # baseInfo.cell(4, 4).text = JsonDict['basic_info']['personal_info']['telephone'] # baseInfo.cell(4, 5).text = 'E-mail' # baseInfo.cell(4, 6).text = JsonDict['basic_info']['personal_info']['email'] setInitCell(baseInfo.cell(4, 1), u'办公电话') setEditCell(baseInfo.cell(4, 2), JsonDict['basic_info']['personal_info']['office_phone']) setInitCell(baseInfo.cell(4, 3), u'手 机') setEditCell(baseInfo.cell(4, 4), JsonDict['basic_info']['personal_info']['telephone']) setInitCell(baseInfo.cell(4, 5), u'E-mail') setEditCell(baseInfo.cell(4, 6), JsonDict['basic_info']['personal_info']['email']) # baseInfo.cell(5, 0).text = u'申请单位情况' setInitCell(baseInfo.cell(5, 0), u'申请单位情况', bold=True) baseInfo.cell(5, 0).merge(baseInfo.cell(6, 0)) # baseInfo.cell(5, 1).text = u'单位名称' # baseInfo.cell(5, 2).text = JsonDict['basic_info']['dep_info']['dep_name'] setInitCell(baseInfo.cell(5, 1), u'单位名称') setEditCell(baseInfo.cell(5, 2), JsonDict['basic_info']['dep_info']['dep_name']) baseInfo.cell(5, 2).merge(baseInfo.cell(5, 3)) # baseInfo.cell(5, 4).text = u'联系人(手机)' setInitCell(baseInfo.cell(5, 4), u'联系人(手机)') baseInfo.cell(5, 4).merge(baseInfo.cell(5, 5)) # baseInfo.cell(5, 6).text = JsonDict['basic_info']['dep_info']['telephone'] setEditCell(baseInfo.cell(5, 6), JsonDict['basic_info']['dep_info']['telephone']) # baseInfo.cell(6, 1).text = u'通信地址' setInitCell(baseInfo.cell(6, 1), u'通信地址') # baseInfo.cell(6, 2).text = JsonDict['basic_info']['dep_info']['address'] setEditCell(baseInfo.cell(6, 2), JsonDict['basic_info']['dep_info']['address']) baseInfo.cell(6, 2).merge(baseInfo.cell(6, 3)).merge(baseInfo.cell( 6, 4)).merge(baseInfo.cell(6, 5)).merge(baseInfo.cell(6, 6)) text = u''' 本人保证所填写的信息均真实有效,无任何虚假信息。本人完全清楚本声明的法律后果,如有不实,愿意承担相应的法律责任。\n %s项目申请人签字: %s\t\t年\t月\t日 ''' % ('\t' * 18, '\t' * 18) # baseInfo.cell(7, 0).text = text setInitCell(baseInfo.cell(7, 0), text) # baseInfo.cell(7, 0).merge(baseInfo.cell(7, 1)).merge(baseInfo.cell(7, 2)).merge(baseInfo.cell(7, 3)).merge(baseInfo.cell(7, 4)).merge(baseInfo.cell(7, 5)).merge(baseInfo.cell(7, 6)) reduce(lambda x, y: x.merge(y), [baseInfo.cell(7, i) for i in xrange(7)]) doc.add_paragraph('\n') ''' 二、主要研究成果(2000字内) ''' research_result_title = doc.add_paragraph() research_result_titleRun = research_result_title.add_run(u'二、主要研究成果') setFont(research_result_titleRun, 16, True, font_HeiTi) research_result_titleRun2 = research_result_title.add_run(u'(2000字内)') setFont(research_result_titleRun2, 16, False, font_FangSong) research_result_instruct = u'\t着重阐述近5年来在国防科技领域取得的代表性研究成果,如在国防基础研究领域取得重大发现,在工程研究领域突破重大技术瓶颈,在重要型号研制中攻克关键技术难题,或转化应用生产重大军事效益。' research_result_instructPara = doc.add_paragraph() research_result_instructRun = research_result_instructPara.add_run( research_result_instruct) setFont(research_result_instructRun, 14, False, font_FangSong) research_result = doc.add_paragraph() research_resultRun = research_result.add_run(JsonDict['research_result'] + '\n') setFont(research_resultRun, 12, False, font_SongTi) doc.add_paragraph('\n') ''' 三、拟展开的研究工作及其军事意义(2000字内) ''' work_and_significance_title = doc.add_paragraph() work_and_significance_titleRun = work_and_significance_title.add_run( u'三、拟展开的研究工作及其军事意义') setFont(work_and_significance_titleRun, 16, True, font_HeiTi) work_and_significance_titleRun2 = work_and_significance_title.add_run( u'(2000字内)') setFont(work_and_significance_titleRun2, 16, False, font_FangSong) work_and_significance_instruct = u'\t着重阐述拟展开的研究工作的创新构思,主要研究方向和初步研究方案,及其军事意义和应用前景。' work_and_significance_instructPara = doc.add_paragraph() work_and_significance_instructRun = work_and_significance_instructPara.add_run( work_and_significance_instruct) setFont(work_and_significance_instructRun, 14, False, font_FangSong) research_result = doc.add_paragraph() research_resultRun = research_result.add_run(JsonDict['research_result'] + '\n') setFont(research_resultRun, 12, False, font_SongTi) doc.add_paragraph('\n') ''' 四、个人简介 ''' personal_profile = doc.add_paragraph() personal_profileRun = personal_profile.add_run(u'四、个人简介') setFont(personal_profileRun, 16, True, font_HeiTi) ''' (一)学习经历(从大学教育填起) ''' learning_exp_title = doc.add_paragraph() learning_exp_titleRun = learning_exp_title.add_run(u'(一)学习经历') setFont(learning_exp_titleRun, 16, True, font_HeiTi) learning_exp_titleRun2 = learning_exp_title.add_run(u'(从大学教育填起)') setFont(learning_exp_titleRun2, 16, False, font_FangSong) learning_exp_number = len(JsonDict['personal_profile']['learning_exp']) learning_exp = doc.add_table(rows=learning_exp_number + 1, cols=4, style='Table Grid') # learning_exp.cell(0, 0).text = u'起止年月' # learning_exp.cell(0, 1).text = u'校(院)及系名称' # learning_exp.cell(0, 2).text = u'专业' # learning_exp.cell(0, 3).text = u'学位' setInitCell(learning_exp.cell(0, 0), u'起止年月') setInitCell(learning_exp.cell(0, 1), u'校(院)及系名称') setInitCell(learning_exp.cell(0, 2), u'专业') setInitCell(learning_exp.cell(0, 3), u'学位') for i in xrange(1, learning_exp_number + 1): # learning_exp.cell(i, 0).text = JsonDict['personal_profile']['learning_exp'][i-1]['start_end_date'] # learning_exp.cell(i, 1).text = JsonDict['personal_profile']['learning_exp'][i-1]['school_name'] # learning_exp.cell(i, 2).text = JsonDict['personal_profile']['learning_exp'][i-1]['major_subject'] # learning_exp.cell(i, 3).text = JsonDict['personal_profile']['learning_exp'][i-1]['bachelor'] setEditCell( learning_exp.cell(i, 0), JsonDict['personal_profile']['learning_exp'][i - 1]['start_end_date']) setEditCell( learning_exp.cell(i, 1), JsonDict['personal_profile']['learning_exp'][i - 1]['school_name']) setEditCell( learning_exp.cell(i, 2), JsonDict['personal_profile']['learning_exp'][i - 1]['major_subject']) setEditCell( learning_exp.cell(i, 3), JsonDict['personal_profile']['learning_exp'][i - 1]['bachelor']) doc.add_paragraph('\n') ''' (二)工作经历(含学术兼职情况) ''' working_exp_title = doc.add_paragraph() working_exp_titleRun = working_exp_title.add_run(u'(二)工作经历') setFont(working_exp_titleRun, 16, True, font_HeiTi) working_exp_titleRun2 = working_exp_title.add_run(u'(含学术兼职情况)') setFont(working_exp_titleRun2, 16, False, font_FangSong) working_exp_number = len(JsonDict['personal_profile']['working_exp']) working_exp = doc.add_table(rows=working_exp_number + 1, cols=3, style='Table Grid') # working_exp.cell(0, 0).text = u'起止年月' # working_exp.cell(0, 1).text = u'工作单位' # working_exp.cell(0, 2).text = u'职务/职称' setInitCell(working_exp.cell(0, 0), u'起止年月') setInitCell(working_exp.cell(0, 1), u'工作单位') setInitCell(working_exp.cell(0, 2), u'职务/职称') for i in xrange(1, working_exp_number + 1): # working_exp.cell(i, 0).text = JsonDict['personal_profile']['working_exp'][i - 1]['start_end_date'] # working_exp.cell(i, 1).text = JsonDict['personal_profile']['working_exp'][i - 1]['working_dep'] # working_exp.cell(i, 2).text = JsonDict['personal_profile']['working_exp'][i - 1]['job'] setEditCell( working_exp.cell(i, 0), JsonDict['personal_profile']['working_exp'][i - 1]['start_end_date']) setEditCell( working_exp.cell(i, 1), JsonDict['personal_profile']['working_exp'][i - 1]['working_dep']) setEditCell(working_exp.cell(i, 2), JsonDict['personal_profile']['working_exp'][i - 1]['job']) doc.add_paragraph('\n') ''' (三)承担国防相关代表性项目情况(限5项) ''' projects_info_title = doc.add_paragraph() projects_info_titleRun = projects_info_title.add_run(u'(三)承担国防相关代表性项目情况') setFont(projects_info_titleRun, 16, True, font_HeiTi) projects_info_titleRun2 = projects_info_title.add_run(u'(限5项)') setFont(projects_info_titleRun2, 16, False, font_FangSong) projects_info_number = len(JsonDict['personal_profile']['projects_info']) projects_info = doc.add_table(rows=projects_info_number + 1, cols=8, style='Table Grid') # projects_info.cell(0, 0).text = u'序号' # projects_info.cell(0, 1).text = u'起止年月' # projects_info.cell(0, 2).text = u'名称' # projects_info.cell(0, 3).text = u'项目类别' # projects_info.cell(0, 4).text = u'来源' # projects_info.cell(0, 5).text = u'经费' # projects_info.cell(0, 6).text = u'本人承担任务' # projects_info.cell(0, 7).text = u'本人排序' setInitCell(projects_info.cell(0, 0), u'序号') setInitCell(projects_info.cell(0, 1), u'起止年月') setInitCell(projects_info.cell(0, 2), u'名称') setInitCell(projects_info.cell(0, 3), u'项目类别') setInitCell(projects_info.cell(0, 4), u'来源') setInitCell(projects_info.cell(0, 5), u'经费') setInitCell(projects_info.cell(0, 6), u'本人承担任务') setInitCell(projects_info.cell(0, 7), u'本人排序') for i in xrange(1, projects_info_number + 1): # projects_info.cell(i, 0).text = JsonDict['personal_profile']['projects_info'][i - 1]['id'] # projects_info.cell(i, 1).text = JsonDict['personal_profile']['projects_info'][i - 1]['start_end_date'] # projects_info.cell(i, 2).text = JsonDict['personal_profile']['projects_info'][i - 1]['project_name'] # projects_info.cell(i, 3).text = JsonDict['personal_profile']['projects_info'][i - 1]['project_type'] # projects_info.cell(i, 4).text = JsonDict['personal_profile']['projects_info'][i - 1]['source'] # projects_info.cell(i, 5).text = JsonDict['personal_profile']['projects_info'][i - 1]['fund'] # projects_info.cell(i, 6).text = JsonDict['personal_profile']['projects_info'][i - 1]['mission'] # projects_info.cell(i, 7).text = JsonDict['personal_profile']['projects_info'][i - 1]['sort'] setEditCell(projects_info.cell(i, 0), JsonDict['personal_profile']['projects_info'][i - 1]['id']) setEditCell( projects_info.cell(i, 1), JsonDict['personal_profile']['projects_info'][i - 1]['start_end_date']) setEditCell( projects_info.cell(i, 2), JsonDict['personal_profile']['projects_info'][i - 1]['project_name']) setEditCell( projects_info.cell(i, 3), JsonDict['personal_profile']['projects_info'][i - 1]['project_type']) setEditCell( projects_info.cell(i, 4), JsonDict['personal_profile']['projects_info'][i - 1]['source']) setEditCell( projects_info.cell(i, 5), JsonDict['personal_profile']['projects_info'][i - 1]['fund']) setEditCell( projects_info.cell(i, 6), JsonDict['personal_profile']['projects_info'][i - 1]['mission']) setEditCell( projects_info.cell(i, 7), JsonDict['personal_profile']['projects_info'][i - 1]['sort']) doc.add_paragraph('\n') ''' (四)代表性成果(论文、著作、研究技术报告、重要学术会议邀请报告,10篇以内第一作者或通信作者,按照重要性排序。每篇应说明申请人的主要贡献,包括:提出的学术思想、创造性、学术刊物中的主要引用及评价情况等。填写顺序:论文、著作、研究技术报告、重要学术会议邀请报告) ''' repr_results_title = doc.add_paragraph() repr_results_titleRun = repr_results_title.add_run(u'(四)代表性成果') setFont(repr_results_titleRun, 16, True, font_HeiTi) repr_results_titleRun2 = repr_results_title.add_run( u'(论文、著作、研究技术报告、重要学术会议邀请报告,10篇以内第一作者或通信作者,按照重要性排序。每篇应说明申请人的主要贡献,包括:提出的学术思想、创造性、学术刊物中的主要引用及评价情况等。填写顺序:论文、著作、研究技术报告、重要学术会议邀请报告)' ) setFont(repr_results_titleRun2, 16, False, font_FangSong) repr_results_instructPara = doc.add_paragraph() repr_results_instructRun = repr_results_instructPara.add_run(u'填写顺序:\n') setFont(repr_results_instructRun, 14, False, font_FangSong) repr_results_instructRun = repr_results_instructPara.add_run( u' 论文:作者(按原排序),题目,期刊名称,卷(期)(年),起止页码;\n') setFont(repr_results_instructRun, 14, False, font_FangSong) repr_results_instructRun = repr_results_instructPara.add_run( u' 著作:作者(按原排序),著作名称,出版社,出版年份,出版地;\n') setFont(repr_results_instructRun, 14, False, font_FangSong) repr_results_instructRun = repr_results_instructPara.add_run( u' 研究技术报告(未公开发表的重要报告):作者(按原排序),报告题目,完成年份;\n') setFont(repr_results_instructRun, 14, False, font_FangSong) repr_results_instructRun = repr_results_instructPara.add_run( u' 重要学术会议邀请报告:作者(按原排序),报告题目,报告年份,会议名称,地点;\n') setFont(repr_results_instructRun, 14, False, font_FangSong) repr_results_to_word_number = len( JsonDict['personal_profile']['repr_results_to_word']) repr_results_to_word = doc.add_table(rows=repr_results_to_word_number * 2 + 1, cols=5, style='Table Grid') # repr_results_to_word.cell(0, 0).text = u'序号' # repr_results_to_word.cell(0, 1).text = u'论著类型' # repr_results_to_word.cell(0, 2).text = u'作者(按原排序)' # repr_results_to_word.cell(0, 3).text = u'题目(名称)' # repr_results_to_word.cell(0, 4).text = u'论著相关信息' setInitCell(repr_results_to_word.cell(0, 0), u'序号') setInitCell(repr_results_to_word.cell(0, 1), u'论著类型') setInitCell(repr_results_to_word.cell(0, 2), u'作者(按原排序)') setInitCell(repr_results_to_word.cell(0, 3), u'题目(名称)') setInitCell(repr_results_to_word.cell(0, 4), u'论著相关信息') for i in xrange(1, repr_results_to_word_number + 1): # repr_results_to_word.cell(i * 2 - 1, 0).text = str(i) # repr_results_to_word.cell(i * 2 - 1, 1).text = JsonDict['personal_profile']['repr_results_to_word'][i - 1]['type'] # repr_results_to_word.cell(i * 2 - 1, 2).text = JsonDict['personal_profile']['repr_results_to_word'][i - 1]['author'] # repr_results_to_word.cell(i * 2 - 1, 3).text = JsonDict['personal_profile']['repr_results_to_word'][i - 1]['title'] # repr_results_to_word.cell(i * 2 - 1, 4).text = JsonDict['personal_profile']['repr_results_to_word'][i - 1]['detail_info'] # repr_results_to_word.cell(i * 2, 1).text = u'主要贡献及引用评价情况:' + JsonDict['personal_profile']['repr_results_to_word'][i - 1]['contribution_refs_info'] setEditCell(repr_results_to_word.cell(i * 2 - 1, 0), str(i)) setEditCell( repr_results_to_word.cell(i * 2 - 1, 1), JsonDict['personal_profile']['repr_results_to_word'][i - 1]['type']) setEditCell( repr_results_to_word.cell(i * 2 - 1, 2), JsonDict['personal_profile']['repr_results_to_word'][i - 1]['author']) setEditCell( repr_results_to_word.cell(i * 2 - 1, 3), JsonDict['personal_profile']['repr_results_to_word'][i - 1]['title']) setEditCell( repr_results_to_word.cell(i * 2 - 1, 4), JsonDict['personal_profile']['repr_results_to_word'][ i - 1]['detail_info']) run = setInitCell( repr_results_to_word.cell(i * 2, 1), u'主要贡献及引用评价情况:', bold=True, alignCentre=False).add_run( JsonDict['personal_profile']['repr_results_to_word'][ i - 1]['contribution_refs_info']) setFont(run, 12, False, font_SongTi) repr_results_to_word.cell(i * 2, 1).merge( repr_results_to_word.cell(i * 2, 2)).merge( repr_results_to_word.cell(i * 2, 3)).merge( repr_results_to_word.cell(i * 2, 4)) repr_results_to_word.cell(i * 2 - 1, 0).merge(repr_results_to_word.cell(i * 2, 0)) doc.add_paragraph('\n') ''' (五)重要科技奖项情况(10项以内) ''' awards_title = doc.add_paragraph() awards_titleRun = awards_title.add_run(u'(五)重要科技奖项情况') setFont(awards_titleRun, 16, True, font_HeiTi) awards_titleRun2 = awards_title.add_run(u'(10项以内)') setFont(awards_titleRun2, 16, False, font_FangSong) awards_instruct = u'\t按顺序填写全部获奖人姓名(按原顺序);获奖项目名称;获奖年份、类别及等级(如1999年国家自然科学二等奖,1998年军队科技进步一等奖等),并分别阐述申请人的主要贡献(限100字)。\n' awards_instructPara = doc.add_paragraph() awards_instructRun = awards_instructPara.add_run(awards_instruct) setFont(awards_instructRun, 14, False, font_FangSong) awards_number = len(JsonDict['personal_profile']['awards']) awards = doc.add_table(rows=awards_number * 2 + 1, cols=6, style='Table Grid') # awards.cell(0, 0).text = u'序号' # awards.cell(0, 1).text = u'全部获奖人' # awards.cell(0, 2).text = u'本人排序' # awards.cell(0, 3).text = u'获奖项目名称' # awards.cell(0, 4).text = u'获奖年份' # awards.cell(0, 5).text = u'获奖情况' setInitCell(awards.cell(0, 0), u'序号') setInitCell(awards.cell(0, 1), u'全部获奖人') setInitCell(awards.cell(0, 2), u'本人排序') setInitCell(awards.cell(0, 3), u'获奖项目名称') setInitCell(awards.cell(0, 4), u'获奖年份') setInitCell(awards.cell(0, 5), u'获奖情况') for i in xrange(1, awards_number + 1): # awards.cell(i * 2 - 1, 0).text = str(i) # awards.cell(i * 2 - 1, 1).text = JsonDict['personal_profile']['awards'][i - 1]['person_name'] # awards.cell(i * 2 - 1, 2).text = JsonDict['personal_profile']['awards'][i - 1]['sort'] # awards.cell(i * 2 - 1, 3).text = JsonDict['personal_profile']['awards'][i - 1]['project_name'] # awards.cell(i * 2 - 1, 4).text = JsonDict['personal_profile']['awards'][i - 1]['year'] # awards.cell(i * 2 - 1, 5).text = JsonDict['personal_profile']['awards'][i - 1]['category'] + JsonDict['personal_profile']['awards'][i - 1]['rank'] # awards.cell(i * 2, 1).text = u'主要贡献:' + JsonDict['personal_profile']['awards'][i - 1]['contribution'] setEditCell(awards.cell(i * 2 - 1, 0), str(i)) setEditCell( awards.cell(i * 2 - 1, 1), JsonDict['personal_profile']['awards'][i - 1]['person_name']) setEditCell(awards.cell(i * 2 - 1, 2), JsonDict['personal_profile']['awards'][i - 1]['sort']) setEditCell( awards.cell(i * 2 - 1, 3), JsonDict['personal_profile']['awards'][i - 1]['project_name']) setEditCell(awards.cell(i * 2 - 1, 4), JsonDict['personal_profile']['awards'][i - 1]['year']) setEditCell( awards.cell(i * 2 - 1, 5), JsonDict['personal_profile']['awards'][i - 1]['category'] + JsonDict['personal_profile']['awards'][i - 1]['rank']) run = setInitCell( awards.cell(i * 2, 1), u'主要贡献:', bold=True, alignCentre=False).add_run( JsonDict['personal_profile']['awards'][i - 1]['contribution']) setFont(run, 12, False, font_SongTi) awards.cell(i * 2, 1).merge(awards.cell(i * 2, 2)).merge(awards.cell(i * 2, 3)).merge(awards.cell(i * 2, 4)).\ merge(awards.cell(i * 2, 5)) awards.cell(i * 2 - 1, 0).merge(awards.cell(i * 2, 0)) doc.add_paragraph('\n') ''' (六)发明专利、国防专利情况(10项以内) ''' patent_title = doc.add_paragraph() patent_titleRun = patent_title.add_run(u'(六)发明专利、国防专利情况') setFont(patent_titleRun, 16, True, font_HeiTi) patent_titleRun2 = patent_title.add_run(u'(10项以内)') setFont(patent_titleRun2, 16, False, font_FangSong) patent_instruct = u'\t请按顺序填写专利申报人(按原排序);专利名称;申请年份、申请号;批准年份、专利号。并分别简述专利实施情况和申请人在专利发明和实施中的主要贡献(100字以内)。\n' patent_instructPara = doc.add_paragraph() patent_instructRun = patent_instructPara.add_run(patent_instruct) setFont(patent_instructRun, 14, False, font_FangSong) patent_number = len(JsonDict['personal_profile']['patent']) patent = doc.add_table(rows=patent_number * 2 + 1, cols=7, style='Table Grid') # patent.cell(0, 0).text = u'序号' # patent.cell(0, 1).text = u'专利申报人' # patent.cell(0, 2).text = u'专利名称' # patent.cell(0, 3).text = u'申请年份' # patent.cell(0, 4).text = u'申请号' # patent.cell(0, 5).text = u'批准年份' # patent.cell(0, 6).text = u'专利号' setInitCell(patent.cell(0, 0), u'序号') setInitCell(patent.cell(0, 1), u'专利申报人') setInitCell(patent.cell(0, 2), u'专利名称') setInitCell(patent.cell(0, 3), u'申请年份') setInitCell(patent.cell(0, 4), u'申请号') setInitCell(patent.cell(0, 5), u'批准年份') setInitCell(patent.cell(0, 6), u'专利号') for i in xrange(1, patent_number + 1): # patent.cell(i * 2 - 1, 0).text = str(i) # patent.cell(i * 2 - 1, 1).text = JsonDict['personal_profile']['patent'][i - 1]['person_name'] # patent.cell(i * 2 - 1, 2).text = JsonDict['personal_profile']['patent'][i - 1]['patent_name'] # patent.cell(i * 2 - 1, 3).text = JsonDict['personal_profile']['patent'][i - 1]['year'] # patent.cell(i * 2 - 1, 4).text = JsonDict['personal_profile']['patent'][i - 1]['application_num'] # patent.cell(i * 2 - 1, 5).text = JsonDict['personal_profile']['patent'][i - 1]['approved_year'] # patent.cell(i * 2 - 1, 6).text = JsonDict['personal_profile']['patent'][i - 1]['patent_num'] # patent.cell(i * 2, 1).text = u'主要贡献及专利实施情况:' + JsonDict['personal_profile']['patent'][i - 1]['contribution_conduct'] setEditCell(patent.cell(i * 2 - 1, 0), str(i)) setEditCell( patent.cell(i * 2 - 1, 1), JsonDict['personal_profile']['patent'][i - 1]['person_name']) setEditCell( patent.cell(i * 2 - 1, 2), JsonDict['personal_profile']['patent'][i - 1]['patent_name']) setEditCell(patent.cell(i * 2 - 1, 3), JsonDict['personal_profile']['patent'][i - 1]['year']) setEditCell( patent.cell(i * 2 - 1, 4), JsonDict['personal_profile']['patent'][i - 1]['application_num']) setEditCell( patent.cell(i * 2 - 1, 5), JsonDict['personal_profile']['patent'][i - 1]['approved_year']) setEditCell( patent.cell(i * 2 - 1, 6), JsonDict['personal_profile']['patent'][i - 1]['patent_num']) run = setInitCell(patent.cell(i * 2, 1), u'主要贡献及专利实施情况:', bold=True, alignCentre=False).add_run( JsonDict['personal_profile']['patent'][ i - 1]['contribution_conduct']) setFont(run, 12, False, font_SongTi) patent.cell(i * 2, 1).merge(patent.cell(i * 2, 2)).merge(patent.cell(i * 2, 3)).merge(patent.cell(i * 2, 4)). \ merge(patent.cell(i * 2, 5)).merge(patent.cell(i * 2, 6)) patent.cell(i * 2 - 1, 0).merge(patent.cell(i * 2, 0)) doc.add_paragraph('\n') ''' 五、单位审核 ''' check_title = doc.add_paragraph() check_titleRun = check_title.add_run(u'五、单位审核') setFont(check_titleRun, 16, True, font_HeiTi) check = doc.add_table(rows=2, cols=2, style='Table Grid') text = u''' %s单位负责人签字: %s (单位公章) %s \t年\t月\t日 ''' % ('\t' * 7, '\t' * 7, '\t' * 7) # check.cell(0, 0).text = u'\n\t单位针对申报书真实性审核意见:' + '\n' * 12 # check.cell(1, 1).text = text setInitCell(check.cell(0, 0), u'\t单位针对申报书真实性审核意见:' + '\n' * 12, alignCentre=False) setInitCell(check.cell(1, 1), text, alignCentre=False) newCell1 = check.cell(0, 0).merge(check.cell(0, 1)) newCell2 = check.cell(1, 0).merge(check.cell(1, 1)) newCell1.merge(newCell2) # doc.save('.\\ExportWord\\' + JsonIO.outputName + '.doc') doc.save('.\\ExportWord\\' + 'test' + '.doc') return True
def creatingfunction_word(self): # word setup page----------------------- # creating document file document = Document() # creating 2 section for separate layout section = document.sections[0] footer = section.footer paragraph = footer.paragraphs[0] # if "PMP" in self.cliname: # paragraph.text = "PAN MALAYSIAN POOL SLA REPORT" # elif "FJB" in self.cliname: paragraph.text = "N’osairis Technology Solutions Sdn Bhd \n " \ "Unit 9-6, Level 9, Tower B, Vertical Business Suite 2, " \ "Avenue 3, Bangsar South, No. 8, Jalan Kerinchi, 59200 Kuala Lumpur." paragraph.style = document.styles["Footer"] paragraph.paragraph_format.left_indent = Inches(-0.5) paragraph.paragraph_format.right_indent = Inches(-0.5) paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER paragraph.underline = True pr = paragraph.runs[0] pr.font.size = Pt(8) pr.font.name = 'Arial' pr.bold = True # creating cover page------------------------------------------ H1 = document.add_paragraph() H1.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT H1_run = H1.add_run('N’OSAIRIS TECHNOLOGY SOLUTIONS' ' CONFIDENTIAL') H1_run.bold = True H1_run.font.size = Pt(20) H1_run.font.name = 'Calibri (Body)' H1_format = H1.paragraph_format H1_format.left_indent = Inches(-0.6) H1_format.right_indent = Inches(-0.6) line = document.add_picture('{}\\line.png'.format(self.rd), width=Inches(7)) last_paragraph = document.paragraphs[-1] last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER last_paragraph_format = last_paragraph.paragraph_format last_paragraph_format.left_indent = Inches(-0.6) last_paragraph_format.right_indent = Inches(-0.6) document.add_paragraph("\n") if "PMP" in self.cliname: logo = document.add_picture('{}\\{}.png'.format( self.rd, self.cliname), width=Inches(4.7), height=Inches(1.1)) elif "FJB" in self.cliname: logo = document.add_picture('{}\\{}.png'.format( self.rd, self.cliname), width=Inches(4.7), height=Inches(1.1)) elif "VINX-EMONEY" in self.cliname or "VINX-WAN" in self.cliname: logo = document.add_picture('{}\\{}.png'.format( self.rd, self.cliname), width=Inches(3.1), height=Inches(1.6)) last_paragraph = document.paragraphs[-1] last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER last_paragraph_format = last_paragraph.paragraph_format last_paragraph_format.left_indent = Inches(-0.7) last_paragraph_format.right_indent = Inches(-0.3) document.add_paragraph("\n") p1 = document.add_paragraph() p1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER if "PMP" in self.cliname: P1_run = p1.add_run('PAN MALAYSIAN POOL AVAILABILITY REPORT') elif "FJB" in self.cliname: P1_run = p1.add_run('FJ Benjamin Holdings Ltd') elif "VINX-EMONEY" in self.cliname or "VINX-WAN" in self.cliname: P1_run = p1.add_run('VINX MALAYSIA SDN. BHD') P1_run.bold = True P1_run.font.size = Pt(18) P1_run.font.name = 'Calibri (Body)' document.add_paragraph("\n\n") p1_1 = document.add_paragraph() p1_1.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER p1_1_run = p1_1.add_run('AVAILABILITY REPORT') p1_1_run.bold = True p1_1_run.font.size = Pt(18) p1_1_run.font.name = 'Calibri (Body)' p2 = document.add_paragraph() p2.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER P2_run = p2.add_run('1 {} {} - {} {} {} '.format( self.month, self.year, self.lastday, self.month, self.year)) P2_run.bold = True P2_run.font.size = Pt(18) P2_run.font.name = 'Calibri (Body)' document.add_paragraph("\n \n \n") p3 = document.add_paragraph() p3.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER P3_run = p3.add_run('Submitted by') P3_run.bold = False P3_run.font.size = Pt(14) P3_run.font.name = 'Calibri (Body)' # document.add_paragraph("\n") document.add_picture('{}\\Nosairis.png'.format(self.rd), width=Inches(1.49), height=Inches(1.8)) last_paragraph = document.paragraphs[-1] last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER # creating section breack ------------------------------ section = document.sections[0] section.page_height = Mm(297) section.page_width = Mm(210) section.start_type = WD_SECTION_START.NEW_PAGE new_section = document.add_section(WD_SECTION_START.NEW_PAGE) print('len(sections) = {}'.format(len(document.sections))) new_section.orientation = WD_ORIENTATION.LANDSCAPE new_width, new_height = new_section.page_height, new_section.page_width new_section.page_width = new_width new_section.page_height = new_height # ============================================= pt = document.add_paragraph() pt.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT Pt_run = pt.add_run('AVAILABILITY REPORT :') Pt_run.bold = True Pt_run.font.size = Pt(14) Pt_run.font.name = 'Calibri (Body)' pt_format = pt.paragraph_format pt_format.left_indent = Inches(-0.5) pt_format.right_indent = Inches(-0.5) pt2 = document.add_paragraph() pt2.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT Pt2_run = pt2.add_run('Date :') Pt2_run.bold = True Pt2_run.font.size = Pt(14) Pt2_run.font.name = 'Calibri (Body)' pt2_format = pt2.paragraph_format pt2_format.left_indent = Inches(-0.5) pt2_format.right_indent = Inches(-0.5) ptd = document.add_paragraph() ptd.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT Ptd_run = pt2.add_run('1 {} {} - {} {} {} '.format( self.month, self.year, self.lastday, self.month, self.year)) Ptd_run.bold = False Ptd_run.font.size = Pt(12) Ptd_run.font.name = 'Calibri (Body)' ptd_format = ptd.paragraph_format ptd_format.left_indent = Inches(-0.5) ptd_format.right_indent = Inches(-0.5) # creating 2nd page (SLA Tables) ptsla = document.add_paragraph() ptsla.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT ptsla_run = ptsla.add_run('SLA Table:') ptsla_run.bold = True ptsla_run.Strickthrough = True ptsla_run.font.size = Pt(14) ptsla_run.font.name = 'Calibri (Body)' ptsla_format = ptsla.paragraph_format ptsla_format.left_indent = Inches(-0.5) ptsla_format.right_indent = Inches(-0.5) # setting the SLA row Tables) if "VINX-WAN" in self.cliname: table = document.add_table(rows=1, cols=8) table_head = [ 'NO', 'Site Name', 'Connectivity', 'Business Hours \n Minutes', 'WAN \n Downtime Minutes', 'Customer \n Downtime Minutes', 'Total Downtime Minutes\n (WAN+Customer)', 'WAN\nAvailability\nPercentage' ] else: table = document.add_table(rows=1, cols=9) table_head = [ 'NO', 'Site Name', 'Connectivity', 'From Date', 'To Date', 'Exact Site Uptime (mins)', 'Total Availability Time (mins)', 'Total downtime', 'Uptime (%)' ] table.style = 'Table Grid' table.alignment = WD_TABLE_ALIGNMENT.CENTER table.allow_autofit = False # ====================================================== nsmap = table._element[0].nsmap # For namespaces searchtag = '{%s}tblPr' % nsmap['w'] # w:tblPr mytag = '{%s}tblInd' % nsmap['w'] # w:tblInd myw = '{%s}w' % nsmap['w'] # w:w mytype = '{%s}type' % nsmap['w'] # w:type for elt in table._element: if elt.tag == searchtag: myelt = lxml.etree.Element(mytag) myelt.set(myw, '-1200') myelt.set(mytype, 'dxa') myelt = elt.append(myelt) #============================================= hdr_cells = table.rows[0].cells # tablehead=list(self.table_list.columns) if "VINX-WAN" in self.cliname: y = 0 while y <= 7: # if y<2: # hdr_cells[y].text = tablehead[y] # else: # hdr_cells[y].text = tablehead[y+1] hdr_cells[y].text = table_head[y] shading_elm = parse_xml(r'<w:shd {} w:fill="e6f026"/>'.format( nsdecls('w'))) hdr_cells[y]._tc.get_or_add_tcPr().append(shading_elm) hdr_cells[y]._tc.tcPr.tcW.type = 'auto' paragraph = hdr_cells[y].paragraphs[0] paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER run = paragraph.runs font = run[0].font font.name = 'Calibri (Body)' font.size = Pt(9) # font size = 30 font.bold = True y += 1 count = 1 for x in self.table_list.sort_values(by='Site Name').index: # 'NO', 'Site Name', 'Connectivity', 'From Date', 'To Date', # 'Exact Site Uptime (mins)', # 'Total Availability Time-Business Hours (mins)', # 'Total downtime_WAN', 'Customer Downtime (mins)', # 'Total Downtime(wan+customer)(mins)', 'Uptime (%) row_cells = table.add_row().cells row_cells[0].text = str(count) row_cells[1].text = str(self.table_list['Site Name'][x]) # row_cells[2].text = str(self.table_list['TNS Router ID'][x]) row_cells[2].text = str(self.table_list['Connectivity'][x]) row_cells[3].text = str(self.table_list[ 'Total Availability Time-Business Hours (mins)'][x]) row_cells[4].text = str( self.table_list['Total downtime_WAN'][x]) # row_cells[5].text = str(self.table_list['Exact Site Uptime (mins)'][x]) row_cells[5].text = str( self.table_list['Customer Downtime (mins)'][x]) row_cells[6].text = str( self.table_list['Total Downtime(wan+customer)(mins)'][x]) row_cells[7].text = str(self.table_list['Uptime (%)'][x]) count += 1 y = 0 while y <= 7: paragraph = row_cells[y].paragraphs[0] row_cells[y]._tc.tcPr.tcW.type = 'auto' if y == 1 or y == 2: paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT else: paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER run = paragraph.runs font = run[0].font font.size = Pt(9) # font size = 30 font.name = 'Calibri (Body)' if float(self.table_list['Uptime (%)'][x]) < self.slaValue: font.color.rgb = RGBColor(0xFF, 0x00, 0x00) else: font.color.rgb = RGBColor(0x00, 0x00, 0x00) y += 1 else: y = 0 while y <= 8: # if y<2: # hdr_cells[y].text = tablehead[y] # else: # hdr_cells[y].text = tablehead[y+1] hdr_cells[y].text = table_head[y] shading_elm = parse_xml(r'<w:shd {} w:fill="e6f026"/>'.format( nsdecls('w'))) hdr_cells[y]._tc.get_or_add_tcPr().append(shading_elm) hdr_cells[y]._tc.tcPr.tcW.type = 'auto' paragraph = hdr_cells[y].paragraphs[0] paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER run = paragraph.runs font = run[0].font font.name = 'Calibri (Body)' font.size = Pt(9) # font size = 30 font.bold = True y += 1 count = 1 for x in self.table_list.sort_values(by='Site Name').index: # 'NO', 'Site Name', 'Connectivity', 'From Date', 'To Date', # 'Exact Site Uptime (mins)', # 'Total Availability Time-Business Hours (mins)', # 'Total downtime_WAN', 'Customer Downtime (mins)', # 'Total Downtime(wan+customer)(mins)', 'Uptime (%) row_cells = table.add_row().cells row_cells[0].text = str(count) row_cells[1].text = str(self.table_list['Site Name'][x]) # row_cells[2].text = str(self.table_list['TNS Router ID'][x]) row_cells[2].text = str(self.table_list['Connectivity'][x]) row_cells[3].text = str(self.table_list['From Date'][x]) row_cells[4].text = str(self.table_list['To Date'][x]) row_cells[5].text = str( self.table_list['Exact Site Uptime (mins)'][x]) row_cells[6].text = str(self.table_list[ 'Total Availability Time-Business Hours (mins)'][x]) row_cells[7].text = str( self.table_list['Total downtime_WAN'][x]) row_cells[8].text = str(self.table_list['Uptime (%)'][x]) count += 1 y = 0 while y <= 8: paragraph = row_cells[y].paragraphs[0] row_cells[y]._tc.tcPr.tcW.type = 'auto' if y == 1 or y == 2: paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT else: paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER run = paragraph.runs font = run[0].font font.size = Pt(9) # font size = 30 font.name = 'Calibri (Body)' if float(self.table_list['Uptime (%)'][x]) < self.slaValue: font.color.rgb = RGBColor(0xFF, 0x00, 0x00) else: font.color.rgb = RGBColor(0x00, 0x00, 0x00) y += 1 #creating new section to add the graphs document.add_page_break() p5 = document.add_paragraph() p5.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT p5_run = p5.add_run('SLA Graphs :') p5_run.bold = True p5_run.font.size = Pt(14) p5_format = p5.paragraph_format p5_format.left_indent = Inches(-0.5) p5_format.right_indent = Inches(-0.5) img_count = 1 while img_count <= self.NoOfgraph: document.add_picture('{}\\{}.png'.format(self.outputadd, img_count), width=Inches(8.2), height=Inches(2.8)) last_paragraph = document.paragraphs[-1] last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER last_paragraph_format = last_paragraph.paragraph_format last_paragraph_format.left_indent = Inches(-0.5) last_paragraph_format.right_indent = Inches(-0.5) img_count += 1 document.save('{}\\{}-{}_SLA_Report.docx'.format( self.outputadd, self.cliname, self.month))
def main(): main_start = time.time() # file name of the report report_file = 'Report.docx' # create the report document report = Document() # path of the input files text_input_path = 'Inputs/Text_input_form.docx' definitions_path = 'Inputs/Terms_definitions.docx' # load text input files with python-docx text_input = Document(text_input_path) definitions = Document(definitions_path) # path to the pictures that must be added to the report picture_paths = Picture.get_picture_paths() # soup of the text input form document text_input_soup = DropDownLists.get_soup(text_input_path) # list of all tables in the order they appear in the text input document, # this is used to get the index of a table in the document tables = [ 'Study table', 'Title table', 'Approval table', 'Cover page caption table', 'Header table', 'Purpose text table', 'Purpose parameter table', 'Purpose caption table', 'Background text table', 'Background parameter table', 'Background caption table', 'Scope text table', 'Scope parameter table', 'Scope caption table', 'EU Regulation 2017/745 definitions table', 'IEC 62366-1 definitions table', 'FDA Guidance definitions table', 'Ethics statement text table', 'Ethics statement parameter table', 'Ethics statement caption table', 'Device specifications text table', 'Device specifications parameter table', 'Device specifications caption table', 'Goal text table', 'Goal parameter table', 'Goal caption table', 'Participants text table', 'Participants parameter table', 'Participants caption table', 'Use environment text table', 'Use environment parameter table', 'Use environment caption table', 'Use scenarios text table', 'Use scenarios parameter table', 'Use scenarios caption table', 'Setup text table', 'Setup parameter table', 'Setup caption table', 'Critical tasks description table', 'Effectiveness analysis decision table', 'Effectiveness analysis tasks and problems table', 'Effectiveness analysis problem type table', 'Effectiveness analysis text table', 'Effectiveness analysis parameter table', 'Effectiveness analysis caption table', 'Time on tasks decision table', 'Time on tasks plot type table', 'Time on tasks table', 'Time on tasks text table', 'Time on tasks parameter table', 'Time on tasks caption table', 'Dwell times and revisits decision table', 'Dwell times and revisits text table', 'Dwell times and revisits parameter table', 'Dwell times and revisits caption table', 'Average fixation decision table', 'Average fixation plot type table', 'Average fixation text table', 'Average fixation parameter table', 'Average fixation caption table', 'Transitions decision table', 'Transitions text table', 'Transitions parameter table', 'Transitions caption table', 'Conclusion text table', 'Conclusion parameter table', 'Conclusion caption table', 'Participants characteristics table' ] # parameters needed to write the report parameters = Parameters.get_all(text_input, text_input_soup, tables) # list of data frames that contain the cGOM data cGOM_dataframes = cGOM.make_dataframes_list() # data frame that contain the Tobii data tobii_data = TobiiData.make_main_dataframe(parameters) # define all styles used in the document Layout.define_all_styles(report) ###### COVER PAGE ###### section1 = report.sections[0] Layout.define_page_format(section1) cover_page_start = time.time() cover_page = CoverPage(report, text_input, tables, picture_paths, parameters) cover_page.create() ''' cover_page_end = time.time() print('Cover page added in %.2f seconds' % (cover_page_end - cover_page_start)) ''' ###### TABLE OF CONTENT ###### report.add_page_break() TableOfContent.write(report) ###### CHAPTERS ###### section2 = report.add_section(WD_SECTION.NEW_PAGE) Layout.define_page_format(section2) footer = Footer(section2) footer.write() header = Header(section2, parameters) header.write() purpose = Chapter(report, text_input, text_input_soup, 'Purpose', tables, picture_paths, parameters) purpose.write_chapter() background = Chapter(report, text_input, text_input_soup, 'Background', tables, picture_paths, parameters) background.write_chapter() scope = Chapter(report, text_input, text_input_soup, 'Scope', tables, picture_paths, parameters) scope.write_chapter() Definitions.write_all_definitions(report, text_input, text_input_soup, definitions, tables) ethics = Chapter(report, text_input, text_input_soup, 'Ethics statement', tables, picture_paths, parameters) ethics.write_chapter() device = Chapter(report, text_input, text_input_soup, 'Device specifications', tables, picture_paths, parameters) device.write_chapter() report.add_paragraph('Test procedure', 'Heading 1') goal = Chapter(report, text_input, text_input_soup, 'Goal', tables, picture_paths, parameters) goal.write_chapter() participants = Chapter(report, text_input, text_input_soup, 'Participants', tables, picture_paths, parameters) participants.write_chapter() environment = Chapter(report, text_input, text_input_soup, 'Use environment', tables, picture_paths, parameters) environment.write_chapter() scenarios = UseScenarios(report, text_input, text_input_soup, 'Use scenarios', tables, picture_paths, parameters) scenarios.write_chapter() setup = Chapter(report, text_input, text_input_soup, 'Setup', tables, picture_paths, parameters) setup.write_chapter() report.add_paragraph('Results', 'Heading 1') start1 = time.time() effectiveness_analysis = EffectivenessAnalysis(report, text_input, text_input_soup, tables, picture_paths, parameters) effectiveness_analysis.write_chapter() end1 = time.time() print('Effectiveness analysis: ', end1 - start1) start2 = time.time() time_on_tasks = TimeOnTasks(report, text_input, text_input_soup, tables, picture_paths, parameters, tobii_data) time_on_tasks.write_chapter() end2 = time.time() print('Time on tasks: ', end2 - start2) start3 = time.time() dwell_times_and_revisits = DwellTimesAndRevisits(report, text_input, text_input_soup, tables, picture_paths, parameters, cGOM_dataframes) dwell_times_and_revisits.write_chapter() end3 = time.time() print('Dwell times: ', end3 - start3) start4 = time.time() average_fixation = AverageFixation(report, text_input, text_input_soup, tables, picture_paths, parameters, cGOM_dataframes) average_fixation.write_chapter() end4 = time.time() print('Average fixation: ', end4 - start4) start5 = time.time() transitions = Transitions(report, text_input, text_input_soup, tables, picture_paths, parameters, cGOM_dataframes) transitions.write_chapter() end5 = time.time() print('Transitions: ', end5 - start5) conclusion = Chapter(report, text_input, text_input_soup, 'Conclusion', tables, picture_paths, parameters) conclusion.write_chapter() DocumentHistory.write(report) ###### APPENDIX ###### report.add_page_break() report.add_paragraph('Appendix', 'Heading 1') Definitions.write_references(report, text_input, text_input_soup, definitions, tables) report.add_page_break() Picture.add_figures_list(report) report.add_page_break() ParticipantsCharacteristics.write(report, text_input, tables, parameters) # save the report report.save(report_file) # error message for the image files that were not added to the report '''Picture.error_message(picture_paths)''' start6 = time.time() # update the table of content update(report_file) end6 = time.time() print('Update: ', end6 - start6) # open the report with the default application for .docx (Word) os.startfile(report_file) end = time.time() print(end - main_start)
class Writer: def __init__(self): # self.filename = "/home/aeront/PycharmProjects/TXLCScreen/FactorTest/waa/Doc/test.docx" # self.path_template = \ # "/home/aeront/PycharmProjects/TXLCScreen/FactorTest/waa/Doc/template.docx" # self.test_pic_path_filename = \ # "/home/aeront/PycharmProjects/TXLCScreen/FactorTest/waa/Doc/test_pic.docx" # if os.path.exists(self.path_template): # self.temp_doc = Document(self.path_template) # else: # print("The template docx does not exist.") # os._exit(1) self.doc = Document() # self.doc = copy.deepcopy(self.temp_doc) # #################################### A4 Paper ##################################### current_section = self.doc.sections[0] current_section.orientation = WD_ORIENTATION.PORTRAIT current_section.page_width = Inches(8.3) current_section.page_height = Inches(11.7) # current_section.footer.text = u"宁波三角洲资产管理有限公司" # #################################### A4 Paper ##################################### def test_report(self, factor_info, df_ic, df_reg, df_gp): factor_id = factor_info[0] path_factor = "".join(["./FactorTest", "/", factor_id]) path_factor_pic = "".join([path_factor, '/', 'Pic']) # path_factor_xls = "".join([path_factor, '/', 'Xls']) path_factor_doc = "".join([path_factor, '/', 'Doc']) index_pic = 1 index_tab = 1 factor_id_cn = factor_info[1] heading_report = "因子: {0}收益率测试".format(factor_id_cn) self.set_heading(heading_report, 1, align_hrz='center') heading_ic = "1, ic 测试" self.set_heading(heading_ic, 2) pic_filename = "".join( [path_factor_pic, "/", factor_id, "_", "bar_ic", ".png"]) self.set_picture(pic_filename) cap_txt = "图{0} ic柱状图".format(index_pic) self.set_pic_caption(cap_txt) index_pic += 1 cap_txt = "表{0} ic值t检验".format(factor_id_cn) self.set_tab_caption(cap_txt) self.set_ic_test_tab(df_ic) index_tab += 1 heading_ic = "2, 截面回归测试" self.set_heading(heading_ic, 2) for ii_index, ii_py in enumerate(df_reg.index.tolist()): pic_filename = "".join([ path_factor_pic, "/", factor_id, "_", "regression", "_", ii_py, ".png" ]) self.set_picture(pic_filename) cap_txt = "图{0} 收益回归测试".format(index_pic) self.set_pic_caption(cap_txt) index_pic += 1 cap_txt = "表{0} {1} 收益回归测试指标".format(index_tab, ii_py) self.set_tab_caption(cap_txt) df_reg_item = df_reg.iloc[ii_index:ii_index + 1, :] self.set_regression_test_tab(df_reg_item) index_tab += 1 heading_gp = "3, 分组测试" self.set_heading(heading_gp, 2) pic_filename = "".join( [path_factor_pic, "/", factor_id, "_", "group", ".png"]) self.set_picture(pic_filename) cap_txt = "图{0} 分组测试净值曲线".format(index_pic) self.set_pic_caption(cap_txt) index_pic += 1 # self.doc.add_page_break() new_section = self.doc.add_section(WD_SECTION.ODD_PAGE) new_width, new_height = new_section.page_height, new_section.page_width new_section.orientation = WD_ORIENT.LANDSCAPE new_section.page_width = new_width new_section.page_height = new_height cap_txt = "表{0} 分组测试指标".format(index_tab, ii_py) self.set_tab_caption(cap_txt) self.set_group_test_tab(df_gp) index_tab += 1 doc_filename = "".join( [path_factor_doc, "/", factor_id, "_", "test", ".docx"]) self.save_file(doc_filename) def set_heading(self, head_txt, head_level, align_hrz='left'): run = self.doc.add_heading("", level=head_level).add_run(head_txt) run.font.color.rgb = RGBColor(0, 0, 0) pr_formant = self.doc.paragraphs[-1].paragraph_format if align_hrz == 'left': pr_formant.alignment = WD_ALIGN_PARAGRAPH.LEFT elif align_hrz == 'right': pr_formant.alignment = WD_ALIGN_PARAGRAPH.RIGHT else: pr_formant.alignment = WD_ALIGN_PARAGRAPH.CENTER def set_picture(self, pic_path_filename): pic = self.doc.add_picture(pic_path_filename) pic.height = int(pic.height * 0.8) pic.width = int(pic.width * 0.8) last_paragraph = self.doc.paragraphs[-1] last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER def set_pic_caption(self, caption_txt): run = self.doc.add_paragraph("").add_run(caption_txt) run.font.color.rgb = RGBColor(0, 0, 0) run.font.bold = True paragraph = self.doc.paragraphs[-1] paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER def set_tab_caption(self, caption_txt): run = self.doc.add_paragraph("").add_run(caption_txt) run.font.color.rgb = RGBColor(0, 0, 0) run.font.bold = True paragraph = self.doc.paragraphs[-1] paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER def set_ic_test_tab(self, df_ic_test): row_num, col_num = df_ic_test.shape table = self.doc.add_table(rows=row_num + 1, cols=col_num, style="Medium Shading 2 Accent 1") table.rows[0].height = Cm(1) table.rows[1].height = Cm(1) table_location_property_dict = dict() heading = table.rows[0].cells heading_list = ["t值", "单边p值"] for ii_value, ii_cell in zip(heading_list, heading): propt = dict() if isinstance(ii_value, str): propt['value'] = ii_value else: propt['value'] = "{0:+.2f}".format(ii_value) propt['bold'] = True propt['size'] = 10 propt['color'] = RGBColor(0, 0, 0) propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER table_location_property_dict[ii_cell] = propt ic_test_ret = df_ic_test.iloc[0, :].tolist() content = table.rows[1].cells for ii_value, ii_cell in zip(ic_test_ret, content): propt = dict() if isinstance(ii_value, str): propt['value'] = ii_value else: propt['value'] = "{0:+.2f}".format(ii_value) propt['bold'] = True propt['size'] = 10 propt['color'] = RGBColor(0, 0, 0) propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER table_location_property_dict[ii_cell] = propt self.dump_data_table(table_location_property_dict, table) def set_regression_test_tab(self, df_rg_test): row_num, col_num = df_rg_test.shape table = self.doc.add_table(rows=row_num + 1, cols=col_num, style="Medium Shading 2 Accent 1") table.rows[0].height = Cm(1) table.rows[1].height = Cm(1) table_location_property_dict = dict() heading = table.rows[0].cells heading_list = [ "f值", "F检验p值", "截距项t值", "截距项t检验p值", "一次项t值", "一次项t检验p值" ] for ii_value, ii_cell in zip(heading_list, heading): propt = dict() if isinstance(ii_value, str): propt['value'] = ii_value else: propt['value'] = "{0:+.2f}".format(ii_value) propt['bold'] = True propt['size'] = 10 propt['color'] = RGBColor(0, 0, 0) propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER table_location_property_dict[ii_cell] = propt rg_test_ret = df_rg_test.iloc[0, :].tolist() content = table.rows[1].cells for ii_value, ii_cell in zip(rg_test_ret, content): propt = dict() if isinstance(ii_value, str): propt['value'] = ii_value else: propt['value'] = "{0:+.2f}".format(ii_value) propt['bold'] = True propt['size'] = 10 propt['color'] = RGBColor(0, 0, 0) propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER table_location_property_dict[ii_cell] = propt self.dump_data_table(table_location_property_dict, table) def set_group_test_tab(self, df_gp_test): row_num, col_num = df_gp_test.shape table = self.doc.add_table(rows=row_num + 1, cols=col_num + 1, style="Medium Shading 2 Accent 1") for ii_row in table.rows: ii_row.height = Cm(0.8) table_location_property_dict = dict() heading = table.rows[0].cells heading_list = [ "分组", "交易日", "净值", "年化收益", "年化波动", "夏普比", "盈利日", "亏损日", "胜率", "盈利平均", "亏损平均", "盈亏比" ] for ii_value, ii_cell in zip(heading_list, heading): propt = dict() if isinstance(ii_value, str): propt['value'] = ii_value else: propt['value'] = "{0:+.2f}".format(ii_value) propt['bold'] = True propt['size'] = 10 propt['color'] = RGBColor(0, 0, 0) propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER table_location_property_dict[ii_cell] = propt heading = table.columns[0].cells[1:] heading_list = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "市场" ] for ii_value, ii_cell in zip(heading_list, heading): propt = dict() if isinstance(ii_value, str): propt['value'] = ii_value else: propt['value'] = "{0:+.2f}".format(ii_value) propt['bold'] = True propt['size'] = 10 if ii_cell != heading[-1]: propt['color'] = RGBColor(0, 0, 0) else: propt['color'] = RGBColor(255, 0, 0) propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER table_location_property_dict[ii_cell] = propt for ii_index, ii_row in enumerate(table.rows[1:]): group_test_ret = df_gp_test.iloc[ii_index, :].values.tolist() content = ii_row.cells[1:] index_item = 0 for ii_value, ii_cell in zip(group_test_ret, content): propt = dict() if index_item in [0, 5, 6]: propt['value'] = str(int(ii_value)) else: propt['value'] = "{0:+.4f}".format(ii_value) index_item += 1 # if isinstance(ii_value, str): # propt['value'] = ii_value # else: # propt['value'] = "{0:+.2f}".format(ii_value) propt['bold'] = False propt['size'] = 10 if ii_index == row_num - 1: propt['color'] = RGBColor(255, 0, 0) else: propt['color'] = RGBColor(0, 0, 0) propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER table_location_property_dict[ii_cell] = propt self.dump_data_table(table_location_property_dict, table) @staticmethod def dump_data_table(table_location_property_dict, table): # table.columns[0].width = Cm(1) for ii_location, ii_propt in table_location_property_dict.items(): if isinstance(ii_location, tuple): cell = table.cell(ii_location[0], ii_location[1]) else: cell = ii_location value = ii_propt.get('value', '') bold = ii_propt.get('bold') para__alignment = ii_propt.get('para_alignment') cell_vertical_alignment = ii_propt.get('cell_vertical_alignment') # cell.text = value run = cell.paragraphs[0].add_run(value) cell.paragraphs[0].paragraph_format.alignment = para__alignment cell.vertical_alignment = cell_vertical_alignment run_font = run.font run_font.size = Pt(ii_propt.get('size')) run_font.color.rgb = ii_propt.get('color') if bold: run_font.bold = bold def test_pic(self): self.doc.add_page_break() new_section = self.doc.add_section(WD_SECTION.ODD_PAGE) section = self.doc.sections[-1] new_width, new_height = section.page_height, section.page_width section.orientation = WD_ORIENT.LANDSCAPE section.page_width = new_width section.page_height = new_height # section.orientation = WD_ORIENT.LANDSCAPE table = self.doc.add_table(rows=12, cols=12) table.style = "Medium Shading 2 Accent 1" table.alignment = WD_TABLE_ALIGNMENT.CENTER heading = table.rows[0].cells heading_list = [ "分组", "交易日", "净值", "年化收益", "年化波动", "夏普比", "盈利日", "亏损日", "胜率", "盈利平均", "亏损平均", "盈亏比" ] for ii_row in table.rows: ii_row.height = Cm(1) for ii_index, ii_item in enumerate(heading_list): cell = heading[ii_index] value = ii_item bold = True para__alignment = WD_ALIGN_PARAGRAPH.CENTER cell_vertical_alignment = WD_ALIGN_VERTICAL.CENTER # cell.text = value run = cell.paragraphs[0].add_run(value) cell.paragraphs[0].paragraph_format.alignment = para__alignment cell.vertical_alignment = cell_vertical_alignment font = run.font font.size = Pt(10.5) run.bold = bold heading = table.columns[0].cells[1:] heading_list = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "市场" ] for ii_index, ii_item in enumerate(heading_list): cell = heading[ii_index] value = ii_item bold = True para__alignment = WD_ALIGN_PARAGRAPH.CENTER cell_vertical_alignment = WD_ALIGN_VERTICAL.CENTER # cell.text = value run = cell.paragraphs[0].add_run(value) cell.paragraphs[0].paragraph_format.alignment = para__alignment cell.vertical_alignment = cell_vertical_alignment font = run.font font.size = Pt(10.5) run.bold = bold cell_pos_list = [(ii_row, ii_col) for ii_row in range(1, 12) for ii_col in range(1, 12)] for ii_cell_pos in cell_pos_list: cell = table.cell(ii_cell_pos[0], ii_cell_pos[1]) value = "{:+.2f}".format(random.randint(-100, 100) * 1.0 / 100) bold = False para__alignment = WD_ALIGN_PARAGRAPH.CENTER cell_vertical_alignment = WD_ALIGN_VERTICAL.CENTER # cell.text = value run = cell.paragraphs[0].add_run(value) cell.paragraphs[0].paragraph_format.alignment = para__alignment cell.vertical_alignment = cell_vertical_alignment font = run.font font.size = Pt(10.5) run.bold = bold if ii_cell_pos[0] == 11: font.color.rgb = RGBColor(255, 0, 0) # table = self.doc.add_table(rows=2, cols=6) # # table.style = "Medium Shading 2 Accent 1" # table.alignment = WD_TABLE_ALIGNMENT.CENTER # # table.autofit = True # # table_location_property_dict = dict() # # location = (0, 0) # propt = dict() # propt['value'] = "f_value" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (0, 1) # propt = dict() # propt['value'] = "F-p_value" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (0, 2) # propt = dict() # propt['value'] = "itcpt:\nt_value" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (0, 3) # propt = dict() # propt['value'] = "itcpt:\nt_p_value" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (0, 4) # propt = dict() # propt['value'] = "linr:\nt_value" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (0, 5) # propt = dict() # propt['value'] = "linr:\nt_p_value" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (1, 0) # propt = dict() # propt['value'] = "6.47" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (1, 1) # propt = dict() # propt['value'] = "0.01" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (1, 2) # propt = dict() # propt['value'] = "1.445" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (1, 3) # propt = dict() # propt['value'] = "0.1485" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (1, 4) # propt = dict() # propt['value'] = "2.5446" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # location = (1, 5) # propt = dict() # propt['value'] = "0.0110" # propt['bold'] = True # propt['size'] = 10 # propt['para_alignment'] = WD_ALIGN_PARAGRAPH.CENTER # propt['cell_vertical_alignment'] = WD_ALIGN_VERTICAL.CENTER # table_location_property_dict[location] = propt # table_location_property_dict[location] = propt # # self.dump_data_table(table_location_property_dict, table) # filter_extension = [u"png"] # path = "/home/aeront/PycharmProjects/TXLCScreen/FactorTest/waa/Pic" # pic_file_list = list() # # for root, dirs, files in os.walk(path): # for filename in files: # filename_extension = filename.split(".")[1] # if filename_extension in filter_extension: # pic_file_list.append(filename) # # for ii_pic in pic_file_list: # # ii_pic_filename = "".join([path, '/', ii_pic]) # pic = self.doc.add_picture(ii_pic_filename) # # last_paragraph = self.doc.paragraphs[-1] # last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER # pic.height = int(pic.height * 0.72) # pic.width = int(pic.width * 0.72) # year_list = \ # ["2007", "2008", "2009", "2010", "2011", "2012", # "2013", "2014", "2015", "2016", "2017", "2018", "2019"] # # for ii_index, ii_year in enumerate(year_list): # # para = self.doc.add_paragraph() # para_format = para.paragraph_format # # headline = "{0}: {1} 收益回归测试\n".format(ii_index, ii_year) # run = para.add_run(headline) # font = run.font # # font.name = "SimSun" # font.size = Pt(14) # font.bold =True # para_format.alignment = WD_ALIGN_PARAGRAPH.LEFT # document = self.temp_doc # table_style = copy.deepcopy(document.tables[-1].style) # self.doc.add_table(14, 14, table_style) def save_file(self, filename): self.doc.save(filename)
class Docx(Report): def __init__(self, dataset, engine, version): super(Docx, self).__init__(engine, version) self.doc = Document() self.init_doc(dataset) def close(self): self.doc.save(self.report_dir + 'Report.v%s.docx' % self.version) def init_doc(self, dataset): self.doc.add_paragraph('').add_run('Data Set').bold = True # write data set count count = dataset.count() row = 0 count_table = self._add_table(2, len(count) + 1) for i, key in enumerate(count.keys()): self._add_text(count_table, row, i, key) self._add_text(count_table, row + 1, i, count[key]) def write(self, name, figname, info): self._write_info(name, info) self._write_score(name, figname) # write feature size def _write_info(self, name, info): if len(self.doc.paragraphs) < 3: self.doc.add_paragraph('').add_run('\n\nFeatures').bold = True feature_table = self._get_table(1) if feature_table is None: ## create feature table row = 0 feature_table = self._add_table(1, 3) self._add_text(feature_table, row, 1, "all features") self._add_text(feature_table, row, 2, "selected features") ## add feature size row = len(feature_table.rows) self._add_row(feature_table) self._add_text(feature_table, row, 0, name) self._add_text(feature_table, row, 1, info[0]) # add graph image def _write_score(self, name, figname): sec = self._get_section(1) if len(self.doc.paragraphs) < 5: self.doc.add_paragraph('').add_run('Evaluation').bold = True score_table = self._get_table(2) if score_table is None: ## create score table row = 0 score_table = self._add_table(1, 3) self._add_text(score_table, row, 1, "accuracy") self._add_text(score_table, row, 2, "auc") ## set column size score_table.columns[0].width = Inches(1.2) score_table.columns[1].width = Inches(2.4) score_table.columns[2].width = Inches(2.4) ## add image row = len(score_table.rows) self._add_row(score_table) self._add_text(score_table, row, 0, name) self._add_img(score_table, row, 1, (self.image_dir + 'accuracy-%s.png' % figname)) self._add_img(score_table, row, 2, (self.image_dir + 'auc-%s.png' % figname)) def _get_section(self, num): if len(self.doc.sections) > num: return self.doc.sections[num] else: return self.doc.add_section() def _get_table(self, num): if len(self.doc.tables) > num: return self.doc.tables[num] return None def _add_table(self, row, col): table = self.doc.add_table(rows=row, cols=col) table.autofit = True return table def _add_row(self, table): table.add_row().cells def _add_text(self, table, row, col, text, center=False): if center == False: table.rows[row].cells[col].text = str(text) else: p = table.rows[row].cells[col].add_paragraph(str(text)) p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER def _add_img(self, table, row, col, img): p = table.rows[row].cells[col].add_paragraph() r = p.add_run() r.add_picture(img, width=Inches(2.2)) p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
style = styles.add_style('QuestionHeader', WD_STYLE_TYPE.PARAGRAPH) font = style.font font.bold = True font.name = 'Open Sans' font.size = Pt(18) styles = document.styles style = styles.add_style('Question', WD_STYLE_TYPE.PARAGRAPH) font = style.font font.name = 'Open Sans' font.size = Pt(18) #add stuff from the list to the pages line by line using the previous styles title = document.add_paragraph(titlePageList[x][1]) title.style = document.styles['Title'] author = document.add_paragraph("By: " + str(titlePageList[x][0])) author.style = document.styles['Name'] new_section = document.add_section(WD_SECTION.ODD_PAGE) qh1 = document.add_paragraph(titlePageList[0][2]) qh1.style = document.styles['QuestionHeader'] q1 = document.add_paragraph(titlePageList[x][2]) q1.style = document.styles['Question'] qh2 = document.add_paragraph(titlePageList[0][3]) qh2.style = document.styles['QuestionHeader'] q2 = document.add_paragraph(titlePageList[x][3]) q2.style = document.styles['Question'] qh3 = document.add_paragraph(titlePageList[0][4]) qh3.style = document.styles['QuestionHeader'] #q3 = document.add_paragraph("I appreciate your interest in my topic. However, I think it is best that we end our discussion now and agree to disagree") q3 = document.add_paragraph(titlePageList[x][4]) q3.style = document.styles['Question'] qh4 = document.add_paragraph(titlePageList[0][5]) qh4.style = document.styles['QuestionHeader']
p2 = document.add_paragraph() p2.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER report_date_sql = "SELECT UNIX_TIMESTAMP(report_date),report_num FROM report_info WHERE report_id=(SELECT MAX(report_id) FROM report_info)" cursor.execute(report_date_sql) report_date_ob = cursor.fetchone() report_date_timestamp = report_date_ob[0] report_date = cntime.chinese_data(report_date_timestamp) run1 = p2.add_run('报告日期 ') run1.font.size = Pt(15.75) run1 = p2.add_run('{}'.format(report_date)) run1.font.size = Pt(15.75) # document.add_page_break() #添加分节后不需要加分页符也会产生新的一页 current_section = document.add_section() current_section.start_type = WD_SECTION.NEW_PAGE header = document.sections[1].header header.is_linked_to_previous = False hdp1 = header.paragraphs[0] hdp1.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT hrun1 = hdp1.add_run('济铁 疾控检 字({}) 第{}号'.format(year, report_num)) hrun1.underline = WD_UNDERLINE.SINGLE hrun1.font.size = Pt(9) hdp2 = header.add_paragraph() hrun2 = hdp2.add_run('检 测 与 评 价 报 告 首 页') hrun2.font.size = Pt(15.75) hrun2 = hdp2.add_run(' \t\t\t\t\t\t共') hrun2.font.size = Pt(9)
def makeDoc(hhs): print "generating document..." doc = Document() #doc.add_paragraph("first page blank") #doc.add_page_break() if titleCheck.get() != 1: section = doc.add_section(WD_SECTION.NEW_PAGE) set_number_of_columns(section, 2) style = doc.styles['Normal'] font = style.font font.name = 'Times New Roman' font.size = Pt(10) paragraph_format = style.paragraph_format paragraph_format.space_before = 0 paragraph_format.space_after = 0 current_settlement = None current_district = None list = None count = 1 for hh in hhs: if titleCheck.get() == 1: if hh.get('settlement') == current_settlement and hh.get( 'chdist') == current_district: if hh.contains('hhcode'): list.add_run( hh.get('hhcode') + ' ' + getHeadName(hh) + '\n') else: list.add_run(str(count) + '. ' + getHeadName(hh) + '\n') count += 1 else: current_settlement = hh.get('settlement') current_district = hh.get('chdist') if list != None: #if this isn't the first dist doc.add_page_break() sec1 = doc.add_section(WD_SECTION.NEW_PAGE) set_number_of_columns(sec1, 1) head = doc.add_paragraph( hh.get('settlement').title() + ': ' + hh.get('chdist').title()) head.alignment = WD_ALIGN_PARAGRAPH.CENTER set = doc.add_paragraph('') set.alignment = WD_ALIGN_PARAGRAPH.CENTER run = set.add_run(hh.get('chdist').title()) run.font.size = Pt(20) count = 1 if hh.contains('hhcode'): first_hh = hh.get('hhcode') + ' ' + getHeadName(hh) + '\n' else: first_hh = str(count) + '. ' + getHeadName(hh) + '\n' list = doc.add_paragraph(first_hh) count += 1 doc.add_page_break() sec2 = doc.add_section(WD_SECTION.NEW_PAGE) set_number_of_columns(sec2, 2) doc = getLineOne(hh, doc) two = doc.add_paragraph(getLineTwo(hh).strip()) three = getLineThree(hh).strip() if len(three) > 0: doc.add_paragraph(three) doc = getLineFour(hh, doc) doc = getChildren(hh, doc, 'cwc') doc = getPrevSpouse(hh, doc, '1w', True) doc = getPrevSpouse(hh, doc, '2w', True) doc = getPrevSpouse(hh, doc, '1h', False) doc = getPrevSpouse(hh, doc, '2h', False) secs = doc.sections for sec in secs: sec.top_margin = Cm(.5) sec.bottom_margin = Cm(.5) sec.left_margin = Cm(.5) sec.right_margin = Cm(.5) try: print "saving to " + outputLocation.get() doc.save(outputLocation.get()) except: print 'permission denied. trying again in 10' time.sleep(10) doc.save(outputLocation.get())
class StwGuidanceService(object): def __init__(self): self.get_appendix5a_data() def get_appendix5a_data(self): self.appendix5a = {} filename = "/Users/mattlavis/sites and projects/1. Online Tariff/download Taric files/resources/appendix5a/Appendix_5a.xlsx" wb = load_workbook(filename) sheet = wb.active max_row = sheet.max_row for i in range(2, max_row + 1): document = str(sheet.cell(row=i, column=1).value).strip() content = str(sheet.cell(row=i, column=4).value).strip() self.appendix5a[document] = content a = 1 def get_measure(self, measure_type_id): self.measure_type_id = measure_type_id self.get_measure_type_description() self.filename_template = "resources/measure_types/template/measure_type_template.docx" self.filename_docx = "resources/measure_types/measure_type_{measure_type_id}_{description}.docx".format( measure_type_id=self.measure_type_id, description=self.measure_type_description2) self.shade_of_grey = parse_xml(r'<w:shd {} w:fill="f0f0f0"/>'.format( nsdecls('w'))) self.lipsum1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id porta orci. Suspendisse eget fringilla augue. Sed blandit iaculis odio, vel pharetra magna gravida id." self.lipsum2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id porta orci. Suspendisse eget fringilla augue. Sed blandit iaculis odio, vel pharetra magna gravida id." self.get_regulations() self.create_document() self.write_measure_type_description() self.add_background() self.add_measure_conditions() self.get_permutations() self.get_footnotes() self.get_geographies() self.get_chapters() self.get_headings() self.get_urls() # Save the file self.save_document() def get_regulations(self): self.regulations_uk = [] self.regulations_xi = [] sql = """ select distinct m.measure_generating_regulation_id from utils.materialized_measures_real_end_dates m where measure_type_id = %s and (validity_end_date is null or validity_end_date::date > current_date)""" # Get the UK version first d = Database("uk") params = [self.measure_type_id] rows = d.run_query(sql, params) if rows: for row in rows: self.regulations_uk.append(row[0]) # Get the XI version next d = Database("xi") params = [self.measure_type_id] rows = d.run_query(sql, params) if rows: for row in rows: self.regulations_xi.append(row[0]) self.regulations_uk = self.format_regulations(self.regulations_uk) self.regulations_xi = self.format_regulations(self.regulations_xi) self.regulations_uk_string = "\n".join(self.regulations_uk) self.regulations_xi_string = "\n".join(self.regulations_xi) def format_regulations(self, regulation_list): regulation_types = { "R": "Regulation", "A": "Agreement", "C": "Draft regulation", "D": "Decision", "I": "Notice", "J": "Judgment", "P": "Regulation", "Q": "Regulation", "R": "Regulation", "S": "Regulation", "V": "Regulation", "X": "Regulation", "Z": "Regulation" } ret = [] for regulation in regulation_list: type = regulation[0:1] year = regulation[1:3] identifer = regulation[3:7] regulation_string = regulation + " (" + regulation_types[ type] + " " + str(identifer) + " / " + year + ")" ret.append(regulation_string) a = 1 return ret def create_document(self): self.document = Document(self.filename_template) self.document._body.clear_content() # Do the title self.document.add_heading( 'Measure type {measure_type_id}'.format( measure_type_id=self.measure_type_id), 0) def add_background(self): self.document.add_heading('Contents', 1) self.insert_toc() self.document.add_heading("Background to the measure", 1) paragraph = self.document.add_paragraph(self.lipsum1, style='Introductory text') paragraph = self.document.add_paragraph(self.lipsum2, style='Normal') def add_measure_conditions(self): self.certificates = {} sql = """select distinct c.code, c.description, m.geographical_area_id from utils.materialized_measures_real_end_dates m, measure_conditions mc, utils.materialized_certificates c where m.measure_sid = mc.measure_sid and mc.certificate_type_code || mc.certificate_code = c.code and m.validity_start_date::date <= current_date and (m.validity_end_date::date >= current_date or m.validity_end_date is null) and measure_type_id = %s order by 1, 3;""" params = [self.measure_type_id] d = Database("uk") rows = d.run_query(sql, params) for row in rows: description = row[1] description = description.replace( "https://www.ecochecker.trade.gov.uk/spirefox5live/fox/spire/OGEL_GOODS_CHECKER_LANDING_PAGE/new", "https://bit.ly/3CTxdFB") description = description.replace( "https://www.gov.uk/government/organisations/export-control-organisation", "https://bit.ly/3N3u1Mf") description = description.replace( "https://www.legislation.gov.uk/eur/2006/1013/contents", "https://bit.ly/3JgKTg5") object = {"description": description, "geography": row[2]} self.certificates[row[0]] = object count = len(self.certificates) new_section = self.document.add_section(WD_SECTION.NEW_PAGE) self.change_orientation_landscape(new_section) self.document.add_heading( "Document codes used with measure type {measure_type_id}".format( measure_type_id=self.measure_type_id), 1) paragraph = self.document.add_paragraph( "Measure type {measure_type_id} features {count} document codes.". format(measure_type_id=self.measure_type_id, count=str(count)), style='Normal') table = self.document.add_table(rows=count + 1, cols=5) # 24.17 widths = (Cm(2.17), Cm(2), Cm(6), Cm(9), Cm(6.57)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells cells[0].text = "Document" cells[1].text = "Geography" cells[2].text = "OTT copy" cells[3].text = "Apdx 5a" cells[4].text = "Commentary" index = 0 for key in self.certificates.keys(): index += 1 cells = table.rows[index].cells cells[0].text = key cells[1].text = self.certificates[key]["geography"] cells[2].text = self.certificates[key]["description"] try: cells[3].text = self.appendix5a[key] except: cells[3].text = "Missing" cells[4].text = "" self.style_table(table, "List Table 3") def save_document(self): self.document.save(self.filename_docx) def get_chapters(self): self.chapters = {} sql = """select distinct (left(m.goods_nomenclature_item_id, 2)) as heading, c.description from utils.materialized_measures_real_end_dates m, utils.materialized_commodities c where (left(m.goods_nomenclature_item_id, 2) || '00000000') = c.goods_nomenclature_item_id and c.productline_suffix = '80' and m.measure_type_id = %s and m.validity_end_date is null order by 1;""" params = [self.measure_type_id] d = Database("uk") rows = d.run_query(sql, params) for row in rows: self.chapters[row[0]] = row[1].capitalize() count = len(self.chapters) self.document.add_heading( "Chapters in which measure type {measure_type_id} is used".format( measure_type_id=self.measure_type_id), 1) paragraph = self.document.add_paragraph( "Measure type {measure_type_id} is used in {count} chapters.". format(measure_type_id=self.measure_type_id, count=str(count)), style='Normal') table = self.document.add_table(rows=count + 1, cols=2) # 17.17 widths = (Cm(2.17), Cm(15)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells cells[0].text = "Chapter" cells[1].text = "Description" index = 0 for key in self.chapters.keys(): index += 1 cells = table.rows[index].cells cells[0].text = key cells[1].text = self.chapters[key] self.style_table(table, "List Table 3") def get_geographies(self): self.geographies = {} sql = """select distinct m.geographical_area_id, ga.description from utils.materialized_measures_real_end_dates m, utils.geographical_areas ga where measure_type_id = %s and m.geographical_area_sid = ga.geographical_area_sid and (m.validity_end_date is null or m.validity_end_date::date > current_date) order by 1;""" params = [self.measure_type_id] d = Database("uk") rows = d.run_query(sql, params) for row in rows: self.geographies[row[0]] = row[1] count = len(self.geographies) self.document.add_heading( "Geographies in which measure type {measure_type_id} is used". format(measure_type_id=self.measure_type_id), 1) paragraph = self.document.add_paragraph( "Measure type {measure_type_id} is used in {count} geographies.". format(measure_type_id=self.measure_type_id, count=str(count)), style='Normal') table = self.document.add_table(rows=count + 1, cols=2) # 17.17 widths = (Cm(4.17), Cm(13)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells cells[0].text = "Geography ID" cells[1].text = "Geography" index = 0 for key in self.geographies.keys(): index += 1 cells = table.rows[index].cells cells[0].text = key cells[1].text = self.geographies[key] self.style_table(table, "List Table 3") def get_footnotes(self): self.footnotes = {} sql = """with cte_footnotes as ( select distinct on (f.footnote_type_id, f.footnote_id) f.footnote_type_id, f.footnote_id, fd.description from footnotes f, footnote_descriptions fd, footnote_description_periods fdp where f.footnote_type_id = fd.footnote_type_id and f.footnote_id = fd.footnote_id and f.footnote_type_id = fdp.footnote_type_id and f.footnote_id = fdp.footnote_id order by f.footnote_type_id, f.footnote_id, fdp.validity_start_date desc ) select distinct (f.footnote_type_id || f.footnote_id) as code, m.geographical_area_id, f.description from cte_footnotes f, utils.materialized_measures_real_end_dates m, footnote_association_measures fam where fam.footnote_type_id = f.footnote_type_id and fam.footnote_id = f.footnote_id and fam.measure_sid = m.measure_sid and m.validity_start_date::date <= current_date and (m.validity_end_date::date >= current_date or m.validity_end_date is null) and m.measure_type_id = %s""" params = [self.measure_type_id] d = Database("uk") rows = d.run_query(sql, params) for row in rows: self.footnotes[row[0]] = {"geography": row[1], "footnote": row[2]} count = len(self.footnotes) self.document.add_heading( "Footnotes used on measure type {measure_type_id}".format( measure_type_id=self.measure_type_id), 1) paragraph = self.document.add_paragraph( "Measure type {measure_type_id} has {count} footnotes.".format( measure_type_id=self.measure_type_id, count=str(count)), style='Normal') table = self.document.add_table(rows=count + 1, cols=3) # 17.17 widths = (Cm(4), Cm(4), Cm(9.17)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells cells[0].text = "Footnote ID" cells[1].text = "Geography" cells[2].text = "Footnote" index = 0 for key in self.footnotes.keys(): index += 1 cells = table.rows[index].cells cells[0].text = key cells[1].text = self.footnotes[key]["geography"] cells[2].text = self.footnotes[key]["footnote"] self.style_table(table, "List Table 3") def get_headings(self): self.headings = {} sql = """select distinct (left(m.goods_nomenclature_item_id, 4)) as heading, c.description from utils.materialized_measures_real_end_dates m, utils.materialized_commodities c where (left(m.goods_nomenclature_item_id, 4) || '000000') = c.goods_nomenclature_item_id and c.productline_suffix = '80' and m.measure_type_id = %s and m.validity_end_date is null order by 1;""" params = [self.measure_type_id] d = Database("uk") rows = d.run_query(sql, params) for row in rows: self.headings[row[0]] = row[1] count = len(self.headings) self.document.add_heading( "Headings in which measure type {measure_type_id} is used".format( measure_type_id=self.measure_type_id), 1) paragraph = self.document.add_paragraph( "Measure type {measure_type_id} is used in {count} headings.". format(measure_type_id=self.measure_type_id, count=str(count)), style='Normal') table = self.document.add_table(rows=count + 1, cols=2) # 17.17 widths = (Cm(2.17), Cm(15)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells cells[0].text = "Heading" cells[1].text = "Description" index = 0 for key in self.headings.keys(): index += 1 cells = table.rows[index].cells cells[0].text = key cells[1].text = self.headings[key] self.style_table(table, "List Table 3") def get_permutations(self): self.permutations = [] sql = """select distinct conditions from utils.materialized_conditions mc where measure_type_id = %s and conditions is not null order by 1;""" params = [self.measure_type_id] d = Database("uk") rows = d.run_query(sql, params) for row in rows: permutation = row[0] self.permutations.append(permutation) new_section = self.document.add_section(WD_SECTION.NEW_PAGE) self.change_orientation_portrait(new_section) count = len(self.permutations) if count == 0: return self.get_permutation_examples() self.document.add_heading( "Permutations in which measure type {measure_type_id} is used". format(measure_type_id=self.measure_type_id), 1) paragraph = self.document.add_paragraph( "Measure type {measure_type_id} is used in {count} permutations.". format(measure_type_id=self.measure_type_id, count=str(count)), style='Normal') table = self.document.add_table(rows=count + 1, cols=3) # 17.17 widths = (Cm(9.17), Cm(3), Cm(5)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells cells[0].text = "Permutation" cells[1].text = "Sample" cells[2].text = "Notes" index = 0 for permutation in self.permutations: index += 1 cells = table.rows[index].cells cells[0].text = permutation try: cells[1].text = self.permutation_examples[permutation][ "goods_nomenclature_item_id"] except: pass try: cells[2].text = self.permutation_examples[permutation][ "description"] except: pass self.style_table(table, "List Table 3") def get_permutation_examples(self): self.permutation_examples = {} for permutation in self.permutations: sql = """ select mc.goods_nomenclature_item_id, c.description, reverse(mc.goods_nomenclature_item_id) from utils.materialized_conditions mc, utils.materialized_commodities c where measure_type_id = %s and mc.goods_nomenclature_item_id = c.goods_nomenclature_item_id and c.productline_suffix = '80' and conditions = %s order by 3 desc limit 1;""" params = [self.measure_type_id, permutation] d = Database("uk") rows = d.run_query(sql, params) if rows: row = rows[0] self.permutation_examples[permutation] = { "goods_nomenclature_item_id": row[0], "description": row[1] } a = 1 def get_measure_type_description(self): sql = """select mtd.description, mt.trade_movement_code from measure_types mt, measure_type_descriptions mtd where mt.measure_type_id = mtd.measure_type_id and mt.measure_type_id = %s;""" params = [self.measure_type_id] d = Database("uk") rows = d.run_query(sql, params) if rows: row = rows[0] self.measure_type_description = row[0] self.trade_movement_code = row[1] else: self.measure_type_description = "" self.trade_movement_code = 0 sys.exit() self.get_flattened_description() self.get_trade_direction() def get_flattened_description(self): self.measure_type_description2 = self.measure_type_description.replace( " ", "_") self.measure_type_description2 = self.measure_type_description2.replace( "(", "") self.measure_type_description2 = self.measure_type_description2.replace( ")", "") self.measure_type_description2 = self.measure_type_description2.lower() def write_measure_type_description(self): table = self.document.add_table(rows=5, cols=2) # 17.17 widths = (Cm(5.17), Cm(12)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells p = cells[0].paragraphs[0] runner = p.add_run("Measure type ID") runner.bold = True cells[1].text = self.measure_type_id cells = table.rows[1].cells p = cells[0].paragraphs[0] runner = p.add_run("Measure type description") runner.bold = True cells[1].text = self.measure_type_description cells = table.rows[2].cells p = cells[0].paragraphs[0] runner = p.add_run("Controlling regulation (UK)") runner.bold = True cells[1].text = self.regulations_uk_string cells = table.rows[3].cells p = cells[0].paragraphs[0] runner = p.add_run("Controlling regulation (XI)") runner.bold = True cells[1].text = self.regulations_xi_string cells = table.rows[4].cells p = cells[0].paragraphs[0] runner = p.add_run("Trade direction") runner.bold = True cells[1].text = self.trade_direction # Set styles and alignments self.style_table(table, "List Table 2") def get_urls(self): self.document.add_heading("Useful URLs", 1) table = self.document.add_table(rows=4, cols=2) # 17.17 widths = (Cm(4.17), Cm(13)) for row in table.rows: for idx, width in enumerate(widths): row.cells[idx].width = width cells = table.rows[0].cells cells[0].text = "Description" cells[1].text = "URL" self.style_table(table, "List Table 3") def get_trade_direction(self): if self.trade_movement_code == 0: self.trade_direction = "Import only" elif self.trade_movement_code == 1: self.trade_direction = "Export only" else: self.trade_direction = "Import / export" def style_table(self, table, style): # Set styles and alignments table.style = style modulator = len(table.rows[0].cells) if style == "List Table 3": # This is for the 1st table only min_row = 1 else: min_row = 0 index = 0 for row in table.rows: for cell in row.cells: index += 1 for para in cell.paragraphs: para.style = self.document.styles['Normal in Table'] if index % modulator == 0: if style == "List Table 2": para.alignment = 2 else: para.alignment = 0 if index % modulator == 1: if index > min_row: shade_of_grey = parse_xml( r'<w:shd {} w:fill="f0f0f0"/>'.format( nsdecls('w'))) cell._tc.get_or_add_tcPr().append(shade_of_grey) for row in table.rows: self.set_cant_split(row) if style == "List Table 3": self.set_repeat_table_header(table.rows[0]) def set_repeat_table_header(self, row): # print("Setting 1st row") """ set repeat table row on every new page """ tr = row._tr trPr = tr.get_or_add_trPr() tblHeader = OxmlElement('w:tblHeader') tblHeader.set(qn('w:val'), "true") trPr.append(tblHeader) return row def set_cant_split(self, row): tr = row._tr trPr = tr.get_or_add_trPr() tblHeader = OxmlElement('w:cantSplit') tblHeader.set(qn('w:val'), "true") trPr.append(tblHeader) return row def change_orientation_landscape(self, section): new_width, new_height = section.page_height, section.page_width section.orientation = WD_ORIENT.LANDSCAPE section.page_width = new_width section.page_height = new_height def change_orientation_portrait(self, section): new_width, new_height = section.page_height, section.page_width section.orientation = WD_ORIENT.PORTRAIT section.page_width = new_width section.page_height = new_height def insert_toc(self): paragraph = self.document.add_paragraph() run = paragraph.add_run() fldChar = OxmlElement('w:fldChar') # creates a new element fldChar.set(qn('w:fldCharType'), 'begin') # sets attribute on element instrText = OxmlElement('w:instrText') instrText.set(qn('xml:space'), 'preserve') # sets attribute on element instrText.text = 'TOC \\o "1-3" \\h \\z \\u' # change 1-3 depending on heading levels you need fldChar2 = OxmlElement('w:fldChar') fldChar2.set(qn('w:fldCharType'), 'separate') # fldChar3 = OxmlElement('w:t') fldChar3 = OxmlElement('w:updateFields') fldChar3.set(qn('w:val'), 'true') # fldChar3.text = "Right-click to update field." fldChar2.append(fldChar3) fldChar4 = OxmlElement('w:fldChar') fldChar4.set(qn('w:fldCharType'), 'end') r_element = run._r r_element.append(fldChar) r_element.append(instrText) r_element.append(fldChar2) r_element.append(fldChar4) p_element = paragraph._p