예제 #1
0
파일: text.py 프로젝트: noraj/MDdot
 def generate(self, rt=None):
     if not rt:
         rt = RichText()
     for i in range(len(self.text)):
         logger.spam("TextNode generation (text | option) : (%s | %s)" %
                     (repr(self.text[i]), self.options[i]))
         rt.add(self.text[i], **(self.options[i]))
     return rt
예제 #2
0
 def format_sum_formula(self, sum_formula: str) -> RichText:
     sum_formula_group = [''.join(x[1]) for x in itertools.groupby(sum_formula, lambda x: x.isalpha())]
     richtext = RichText('')
     if sum_formula_group:
         for _, word in enumerate(sum_formula_group):
             if isnumeric(word):
                 richtext.add(word, subscript=True)
             else:
                 richtext.add(word)
         return richtext
     else:
         return RichText('No sum formula')
	def process_attachment_file(self, input_path, output_path, target=None):
		try:		
			output_path, _ = os.path.splitext(output_path)
			output_path += '.DOCX'		
			doc = DocxTemplate(input_path)
			rt = RichText()
			template_vars = mailer.render_DOC_template_var(self.application.config, target)
			rt.add('Alibaba',url_id=doc.build_url_id(template_vars['url']['webserver']))
			context = {'target_name': template_vars['client']['first_name'], 'target_email_address': template_vars['client']['email_address'], 'secret_id': template_vars['uid'], 'example': rt }	
			doc.render(context)
			doc.save(output_path)		
			return output_path
		except:
			return 0	
예제 #4
0
 def _get_bonds_list(self, without_h):
     bonds = []
     num = 1
     newsymms = {}
     symms = {}
     for at1, at2, dist, symm2 in self.cif.bonds(without_h):
         dist = dist.replace('-', minus_sign)
         if symm2 == '.':
             symm2 = None
         num = symmsearch(self.cif, newsymms, num, symm2, symms)
         # Atom1 - Atom2:
         a = '{}{}{}'.format(at1, halbgeviert, at2)
         symm = '#' + str(symms[symm2]) if symm2 else ''
         atoms = RichText(a)
         atoms.add(symm, superscript=True)
         bonds.append({'atoms': atoms, 'dist': dist})
         self.bonds_as_string.append({'atoms': a, 'symm': symm, 'dist': dist})
     self._symmlist.update(newsymms)
     return bonds
예제 #5
0
 def _get_hydrogen_bonds(self) -> List[dict]:
     symms = {}
     newsymms = {}
     num = 1
     atoms_list = []
     for h in self.cif.hydrogen_bonds():
         symm = h.symm
         if symm == '.':
             symm = None
         num = symmsearch(self.cif, newsymms, num, symm, symms)
         symmval = ('#' + str(symms[symm])) if symm else ''
         a = h.label_d + halbgeviert + h.label_h + ellipsis_mid + h.label_a
         atoms = RichText(a)
         atoms.add(symmval, superscript=True)
         atoms_list.append({'atoms'  : atoms, 'dist_dh': h.dist_dh, 'dist_ha': h.dist_ha,
                            'dist_da': h.dist_da, 'angle_dha': h.angle_dha})
         self.hydrogen_bonds_as_str.append({'atoms'  : a, 'dist_dh': h.dist_dh, 'dist_ha': h.dist_ha,
                                            'dist_da': h.dist_da, 'angle_dha': h.angle_dha, 'symm': symmval})
     self._symmlist = newsymms
     return atoms_list
예제 #6
0
 def _get_angles_list(self, without_h):
     angles_list = []
     newsymms = {}
     symms = {}
     num = 1
     for ang in self.cif.angles(without_h):
         symm1 = ang.symm1
         symm2 = ang.symm2
         if ang.symm1 == '.':
             symm1 = None
         if ang.symm2 == '.':
             symm2 = None
         num = symmsearch(self.cif, newsymms, num, symm1, symms)
         num = symmsearch(self.cif, newsymms, num, symm2, symms)
         symm1_str = '#' + str(symms[symm1]) if symm1 else ''
         symm2_str = '#' + str(symms[symm2]) if symm2 else ''
         angle_val = ang.angle_val.replace('-', minus_sign)
         # atom1 symm1_str a symm2_str
         atoms = RichText(ang.label1)
         atoms.add(symm1_str, superscript=True)
         a = '{}{}{}{}'.format(halbgeviert, ang.label2, halbgeviert, ang.label3)
         atoms.add(a, superscript=False)
         atoms.add(symm2_str, superscript=True)
         angles_list.append({'atoms': atoms, 'angle': angle_val})
         self.angles_as_string.append({'atom1': ang.label1,
                                       'atom2': a,
                                       'symm1': symm1_str,
                                       'symm2': symm2_str,
                                       'angle': angle_val})
     self._symmlist.update(newsymms)
     return angles_list
예제 #7
0
def make_doc_file(bkm_info_list):
    '''Gegernate a BKM meeting invitation message'''
    tpl = DocxTemplate('meeting_invitation_message_template.docx')
    result = []
    for bkm_info in bkm_info_list:
        dic = {}
        dic['bkm_nums'] = bkm_info.get()[0]
        bkm_pdf_link = bkm_info.get()[5]
        rt = RichText()
        rt.add(bkm_info.get()[1],
               url_id=tpl.build_url_id(bkm_pdf_link),
               color='blue',
               underline=True)
        dic['bkm_titles'] = rt
        dic['authors'] = bkm_info.get()[2]
        dic['apprs'] = bkm_info.get()[3]
        dic['create_dates'] = bkm_info.get()[4]

        result.append(dic)
    print('成功获取BKM数据, 正在将数据写入模板......')
    context = {'bkm': result}

    tpl.render(context)
    tpl.save('meeting_invitation_message.docx')
예제 #8
0
 def _get_torsion_angles_list(self, without_h: bool):
     if not self.cif.nangles(without_h) > 0:
         return []
     symms = {}
     newsymms = {}
     num = 1
     torsion_angles = []
     for tors in self.cif.torsion_angles(without_h):
         symm1, symm2, symm3, symm4 = tors.symm1, tors.symm2, tors.symm3, tors.symm4
         if tors.symm1 == '.':
             symm1 = None
         if tors.symm2 == '.':
             symm2 = None
         if tors.symm3 == '.':
             symm3 = None
         if tors.symm4 == '.':
             symm4 = None
         num = symmsearch(self.cif, newsymms, num, symm1, symms)
         num = symmsearch(self.cif, newsymms, num, symm2, symms)
         num = symmsearch(self.cif, newsymms, num, symm3, symms)
         num = symmsearch(self.cif, newsymms, num, symm4, symms)
         symmstr1 = '#' + str(symms[symm1]) if symm1 else ''
         symmstr2 = '#' + str(symms[symm2]) if symm2 else ''
         symmstr3 = '#' + str(symms[symm3]) if symm3 else ''
         symmstr4 = '#' + str(symms[symm4]) if symm4 else ''
         atoms = RichText(tors.label1)
         atoms.add(symmstr1, superscript=True)
         atoms.add(halbgeviert)
         atoms.add(tors.label2)
         atoms.add(symmstr2, superscript=True)
         atoms.add(halbgeviert)
         atoms.add(tors.label3)
         atoms.add(symmstr3, superscript=True)
         atoms.add(halbgeviert)
         atoms.add(tors.label4)  # labels
         atoms.add(symmstr4, superscript=True)
         angle = tors.torsang.replace('-', minus_sign)
         torsion_angles.append({'atoms': atoms, 'angle': angle})
         self.torsion_angles_as_string.append({'atom1': tors.label1,
                                               'atom2': tors.label2,
                                               'atom3': tors.label3,
                                               'atom4': tors.label4,
                                               'symm1': symmstr1,
                                               'symm2': symmstr2,
                                               'symm3': symmstr3,
                                               'symm4': symmstr4,
                                               'angle': angle})
     self._symmlist = newsymms
     return torsion_angles
예제 #9
0
파일: aniu.py 프로젝트: aniu98/myPython
applicationSrcYml = "./template/application.yml"
applicationDestYml = destFilePath + "application.yml"
shutil.copy(applicationSrcYml, applicationDestYml)

lastVersionYml = baseDir + "统一业务门户前台应用-V" + lastVersion + "/" + 'application.yml'
file1 = open(lastVersionYml, 'r', encoding='UTF-8').readlines()
file2 = open(applicationSrcYml, 'r', encoding='UTF-8').readlines()
# diff = difflib.ndiff(file1, file2)
# sys.stdout.writelines(diff)
d = difflib.Differ()
list1 = list(d.compare(file1, file2))

rt = RichText("")
for line in list1:
    if line[0] == "?": list1.remove(line)
    if line[0] == '-': rt.add(line.replace('-', '', 1), strike=True)
    if line[0] == '+': rt.add(line.replace('+', '', 1), color='#ff0000')
    if line[0] == ' ': rt.add(line.replace(' ', '', 1))
# with open(destFilePath+"diff.yml", 'w') as file_object:
#     # file_object.write(list1)
#     for line in list1:
#         # file_object.write("\n")
#         file_object.write(line)
data_dic = {
    'version': version,
    "author": author,
    "year": 2020,
    "month": 8,
    "day": 31,
    'yml': rt,
    'apinNum': 167
예제 #10
0
# -*- coding: utf-8 -*-
'''
Created : 2015-03-26

@author: Eric Lapouyade
'''

from docxtpl import DocxTemplate, RichText

tpl=DocxTemplate('test_files/richtext_tpl.docx')

rt = RichText('an exemple of ')
rt.add('a rich text', style='myrichtextstyle')
rt.add(' with ')
rt.add('some italic', italic=True)
rt.add(' and ')
rt.add('some violet', color='#ff00ff')
rt.add(' and ')
rt.add('some striked', strike=True)
rt.add(' and ')
rt.add('some small', size=14)
rt.add(' or ')
rt.add('big', size=60)
rt.add(' text.')
rt.add(' Et voilà ! ')
rt.add('\n1st line')
rt.add('\n2nd line')
rt.add('\n3rd line')
rt.add('\n\n<cool>')

context = {
예제 #11
0
 def richtext(self):
     r = RichText('')
     if self.authors:
         r.add(self.authors)
         r.add(', ')
     if self.journal:
         r.add(self.journal, italic=True)
         if not self.journal.endswith('.'):
             r.add(', ')
         else:
             r.add(' ')
     if self.year:
         r.add(self.year, bold=True)
         r.add(', ')
     if self.volume:
         r.add(self.volume, italic=True)
         r.add(', ')
     if self.pages:
         r.add(self.pages)
         if self.doi:
             r.add(', ')
     if self.doi:
         r.add(self.doi)
     if any([self.journal, self.pages, self.year, self.volume, self.doi]):
         r.add('.')
     return r
예제 #12
0
def download_report(request, pk):
    p = Project.objects.get(id=pk, user=request.user)
    if p:
        try:
            select_module = getselectmodule(pk, request.user)
            rt = RichText()
            modules = ''
            for module in select_module:
                modules += module.module_name + '、'
                rt.add(module.module_name, style='header1')
                rt.add('\a')
                tables = ProjectTable.objects.filter(project=pk, module=module)
                for table in tables:
                    rt.add(table.table.table_name, style='header2')
                    rt.add('\a')
                    data = list(
                        Value.objects.filter(project_table=table.id).values())
                    columns = Column.objects.filter(table=table.table)
                    line = 1
                    if data:
                        vals = []
                        for key, val in enumerate(data):  # 遍历数据
                            if val['line'] != line:  # 换行
                                rt.add('。\a')
                                line = val['line']
                            separater = ','
                            if (key + 1 < len(data)
                                    and data[key + 1]['line'] != line):
                                separater = ''
                            elif (key + 1 == len(data)):
                                separater = '。'
                            # 生成单元格内容
                            column = columns.filter(id=val['column_id'])[0]
                            value = column.column_name
                            if column.parameter is not None:
                                value += '(参数名:' + column.parameter + ')'
                                if column.formula is not None:
                                    #  有参数名,又有公式的情况
                                    value += '的计算公式为:' + column.formula + separater
                                    value += '计算结果是' + val['value'] + separater
                                else:
                                    value += '是' + val['value'] + separater
                            #  没有参数名,有公式的情况
                            elif column.formula is not None:
                                value += '的计算公式为:' + column.formula + separater
                                value += '计算结果是' + val['value'] + separater
                            else:
                                #  没有参数名,没有公式的情况
                                value += '是' + val['value'] + separater
                            rt.add(value, style='标题 4')
                        rt.add('\a')

            data = {
                'project_name': p.project_name,
                'project_num': p.project_num,
                'project_text': p.project_text,
                'designer': p.designer,
                'proofreader': p.proofreader,
                'chief': p.chief,
                'approver': p.approver,
                'version': p.version,
                'select_module': modules.strip('、'),
                'rt': rt,
            }

        except Exception as e:
            return json_error(e)

        # 删除生成的报告
        filepath = os.getcwd() + '/templates/project'
        filename = '项目报告.docx'  # 所生成的word文档需要以.docx结尾,文档格式需要
        # delete_docx_file(filepath)       # 收到每个请求后,会将文件当中的非模板文件删除
        template_path = filepath + '/project_tpl.docx'
        template = DocxTemplate(template_path)
        template.render(context=data)
        template.save(os.path.join(filepath, filename))
        response = StreamingHttpResponse(
            read_file(os.path.join(filepath, filename), 512))
        response[
            'Content-Type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        response['Content-Disposition'] = 'attachment;filename="{}"'.format(
            filename)
        # time.sleep(10)
        return response
    else:
        return json_error('项目不存在')
예제 #13
0
    generated_path = get_full_path(r'generated.docx')
    context_path = get_full_path(r'inject.json')

    # Open document
    doc = DocxTemplate(template_path)

    # Read context
    replacements = read_json(context_path)

    # Replace variable
    context = copy.copy(replacements['variables'])

    # Replace images
    for image, data in replacements['images'].items():
        context[image] = InlineImage(doc, data[0], width=Mm(data[1]))

    # Replace URLs
    for url, data in replacements['urls'].items():
        rt = RichText()
        rt.add(data[0], url_id=doc.build_url_id(data[1]))
        context[url] = rt

    # Replace tables
    for table, data in replacements['tables'].items():
        context[table + '_col_labels'] = data['col_labels']
        context[table + '_tbl_contents'] = data['tbl_contents']

    # Save new file
    doc.render(context)
    doc.save(generated_path)
예제 #14
0
from docxtpl import DocxTemplate, InlineImage, RichText
from docx.shared import Mm, Inches, Pt
import jinja2

tpl = DocxTemplate('fujian03.docx')

rt_hukou = RichText('')
rt_hukou.add('内蒙古突泉县', size=12)  # 字体大小
rt_id_number = RichText('')
rt_id_number.add('内蒙古突泉县', size=12)  # 字体大小
rt_p_status = RichText('')
rt_p_status.add('共青团员', size=12)  # 字体大小

id_number = '152224199101104567'

context = {
    'r_e': '韩小顺',
    'sa': '男',
    'bir': '1991-01-10',
    'edu': '本科',
    'id_number': '15222419910110651x',
    'work_unit': '青峰白羽软件技术工作室',
    'f_p': '021-09765432',
    'u_n': '私营企业',
    'profession': '计算机软件',
    's_w_d': '2015-08-20',
    'cl': '4',
    'hukou': rt_hukou,
    'address': '北京大兴区旧宫镇',
    'unit_address': '北京大兴区旧宫镇',
    'email': '北京大兴区旧宫镇',
예제 #15
0
# -*- coding: utf-8 -*-
'''
Created : 2015-03-26

@author: Eric Lapouyade
'''

from docxtpl import DocxTemplate, RichText

tpl = DocxTemplate('test_files/richtext_tpl.docx')

rt = RichText('an exemple of ')
rt.add('a rich text', style='myrichtextstyle')
rt.add(' with ')
rt.add('some italic', italic=True)
rt.add(' and ')
rt.add('some violet', color='#ff00ff')
rt.add(' and ')
rt.add('some striked', strike=True)
rt.add(' and ')
rt.add('some small', size=14)
rt.add(' or ')
rt.add('big', size=60)
rt.add(' text.')
rt.add(' Et voilà ! ')
rt.add('\n1st line')
rt.add('\n2nd line')
rt.add('\n3rd line')
rt.add('\n\n<cool>')
rt.add('\nFonts :\n', underline=True)
rt.add('Arial\n', font='Arial')
예제 #16
0
table = {'tbl_contents': context}
'''
table = {
    'user_labels': ['fruit', 'vegetable', 'stone', 'thing'],
    'tbl_contents': [
        {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']},
        {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']},
        {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']},
    ],
}
'''

tpl = DocxTemplate(
    r'C:/工作/典型事件/手机POS交易数据疑似套现/拉卡拉商户交易明细/商户交易日监测报告/商户交易日监测报告_tpl.docx')
rt_date = RichText()
rt_date.add(time_str + '\n', font='方正小标宋简体', size=44)
rt_pargh1 = RichText()
rt_pargh1.add(
    time_str + '新增商户' + str(mchnt_curr_day) + '家,新增交易笔数' +
    str(trans_num_curr_day) + '笔,新增交易金额' + str(round(trans_at_curr_day, 2)) +
    '元,贷记卡交易金额占比为' + format(trans_at_loan_curr_day, '.2%') + '。本日活跃商户数为:' +
    str(mchnt_day_live) + ',本周活跃商户数为:' + str(mchnt_week_live) + ',本月活跃商户数为:' +
    str(mchnt_month_live) + ',本日交易金额为过去30天均值的' +
    str(round(trans_at_30_ratio, 2)) + '倍' + ',交易笔数为过去30天均值的' +
    str(round(trans_num_30_ratio, 2)) + '倍' + ',贷记卡交易金额为过去30天均值的' +
    str(round(loan_trans_at_30_ratio, 2)) + '倍' + ',贷记卡交易笔数为过去30天均值的' +
    str(round(loan_trans_num_30_ratio, 2)) + '倍' + ',5000元以上贷记卡交易金额为过去30天均值的' +
    str(round(loan_trans_5000_at_30_day_ratio, 2)) + '倍' +
    ',5000元以上贷记卡交易笔数为过去30天均值的' +
    str(round(loan_trans_5000_num_30_day_ratio, 2)) + '倍' + ',本日uMP上送率为' +
    str(round(uMP_upload_ratio, 4) * 100) + '%' + ',当日疑似危险商户有' +
예제 #17
0
def markdown_to_docx(text, tpl):
    # Credits: epompeii
    rt = RichText('')
    soup = BeautifulSoup(
        '<html>' +
        docassemble.base.filter.markdown_to_html(text, do_terms=False) +
        '</html>', 'lxml')
    html_tag = soup.find("html")
    for html_element in html_tag.next_elements:
        if (html_element.name):
            for html_key, html_value in html_names.items():
                if (html_element.name == html_key):
                    if (html_element.name == 'p'):
                        rt.add('\a' + html_element.text + ' ')
                    elif (html_element.name == 'em'):
                        rt.add(html_element.text, italic=html_value)
                        rt.add(' ')
                    elif (html_element.name == 'strong'):
                        rt.add(html_element.text, bold=html_value)
                        rt.add(' ')
                    elif (html_element.name == 'u'):
                        rt.add(html_element.text, underline=html_value)
                        rt.add(' ')
                    elif (html_element.name == 'strike'):
                        rt.add(html_element.text, strike=html_value)
                        rt.add(' ')
                    elif (html_element.name == 'a'):
                        rt.add(html_element.text,
                               url_id=tpl.build_url_id(html_element['href']),
                               underline=html_value)
                        rt.add(' ')
                    elif (html_element.name == 'code'):
                        rt.add(html_element.text, italic=html_value)
                        rt.add(' ')
                    elif (html_element.name == 'h1'
                          or html_element.name == 'h2'
                          or html_element.name == 'h3'
                          or html_element.name == 'h4'):
                        rt.add('\n')
                        rt.add(html_element.text, size=html_value)
                        rt.add('\n')
                    elif (html_key == 'br' or html_key == 'ol'
                          or html_key == 'ul'):
                        rt.add('\n')
                    elif (html_key == 'li'):
                        rt.add('-' + html_element.text + '\n')
    logmessage(unicode(rt))
    return rt
예제 #18
0
def GetRichText(richElements):
    rt = RichText()
    for element in richElements:
        if (element.name == 'b'):
            rt.add(unicodedata.normalize('NFKD', element.text).encode(
                'ascii', 'ignore'),
                   bold=True)
            rt.add('\n')
        elif (element.name == 'i'):
            rt.add(unicodedata.normalize('NFKD', element.text).encode(
                'ascii', 'ignore'),
                   italic=True)
            rt.add('\n')
        elif (element.name == 'u'):
            rt.add(unicodedata.normalize('NFKD', element.text).encode(
                'ascii', 'ignore'),
                   underline=True)
            rt.add('\n')
        elif (isinstance(element, NavigableString)):
            rt.add(element)
        elif (element.name == 'br'):
            rt.add('\n')
        elif (element.name == 'ul'):
            rt.add(element.text)
        elif (element.name == 'img'):
            filename = element.attrs['src']
            rt.add('Embedded Image',
                   url_id=doc.build_url_id(filename),
                   bold=True,
                   color='0000EE',
                   underline=True)
            #requ = urllib.request.urlopen(filename)
            #imgBytes = requ.read();
            #pict =
            #"""{\pict\picscalex125\picscaley125\piccropl0\piccropr0\piccropt0\piccropb0\picw7789\pich9102\picwgoal4416\pichgoal5160\wmetafile8\bliptag-198017951"""
            #rt.add(pict);
        elif (element.name == 'a'):
            if 'href' in element.attrs:
                href = element.attrs['href']
                rt.add(element.text,
                       url_id=doc.build_url_id(href),
                       bold=True,
                       color='0000EE',
                       underline=True)
        elif (element.name == 'font' or element.name == 'p'
              or element.name == 'span' or element.name == 'div'):
            if element.attrs:
                for keys in element.attrs:
                    if (keys == 'color'):
                        rt.add(unicodedata.normalize(
                            'NFKD',
                            element.text + ' ').encode('ascii', 'ignore'),
                               color=element.attrs[keys])
                    if (keys == 'style'):
                        rt.add(unicodedata.normalize(
                            'NFKD',
                            element.text + ' ').encode('ascii', 'ignore'),
                               style=element.attrs[keys])
            else:
                rt.add(
                    unicodedata.normalize('NFKD', element.text + ' ').encode(
                        'ascii', 'ignore'))
        elif (element.name == 'li'):
            continue
        else:
            rt.add(element.text)
    return rt
def create_data(student_infos):
    system_type = platform.system()
    # if 'indows' in system_type:
    #     data = pd.read_excel("D:/PycharmProjects/lelingzdy/baoming/webapp/utils/all_info.xlsx",
    #                          sheet_name='按工种统计')
    # else:
    #     data = pd.read_excel("/data/python3_space/lelingzdy/baoming/webapp/utils/all_info.xlsx",
    #                          sheet_name='按工种统计')
    # 职业(工种)	级别	身份类型		中文名	英文名	性别	
    # 出生日期	工作单位	从事职业	民族	本工种职业年限	
    # 文化程度	参加工作日期	考生来源	来源省份	来源地区	
    # 现役军人	下岗人员	失业人员	残疾人员	农民工	两劳人员	
    # 其他	在校学生	联系电话	手机	身份地址	常住地址	
    # 邮政编码	政治面貌	报名点	鉴定科目	鉴定类型	原证书号	
    # 申报条件	报名备注	补贴类型	补贴证件类型	补贴证件号码	预报考点

    if len(student_infos) > 0:
        tmp_num = 0
        data = pd.DataFrame([['职业(工种)',
                              '级别',
                              '身份类型',
                              '中文名',
                              '英文名',
                              '性别',
                              '出生日期',
                              '工作单位',
                              '从事职业',
                              '民族',
                              '本工种职业年限',
                              '文化程度',
                              '参加工作日期',
                              '考生来源',
                              '来源省份',
                              '来源地区',
                              '现役军人',
                              '下岗人员',
                              '失业人员',
                              '残疾人员',
                              '农民工',
                              '两劳人员',
                              '其他',
                              '在校学生',
                              '联系电话',
                              '手机',
                              '身份地址',
                              '常住地址',
                              '邮政编码',
                              '政治面貌',
                              '报名点',
                              '鉴定科目',
                              '鉴定类型',
                              '原证书号',
                              '申报条件',
                              '报名备注',
                              '补贴类型',
                              '补贴证件类型',
                              '补贴证件号码',
                              '预报考点']])
        # # data.loc[0] =
        # data.loc[1] = ['序号',
        #                '姓名',
        #                '身份证号码',
        #                '性别',
        #                '拟报工种',
        #                '级别',
        #                '已交费金额',
        #                '欠交费金额',
        #                '电话',
        #                '单位名称',
        #                '负责报名的负责人',
        #                '备注'
        #                ]
        for student in student_infos:
            identification_level = str(student.identification_level)
            if len(identification_level) > 0:
                identification_level = worker_level[str(student.identification_level)]
            else:
                identification_level = ''
                # 原证书编号
            original_certificate_number = student.original_certificate_number
            if original_certificate_number:
                pass
            else:
                original_certificate_number = ""

            if student.issuance_time:
                issuance_time = student.issuance_time
            else:
                issuance_time = ''

                # 文化程度
            education_degree = student.user_info.education_degree
            if education_degree:
                education_name = student.user_info.education_degree.education_name
            else:
                education_name = ''
            # data.loc[i + 4] = [1, '韩小顺', '男', '152224199101105555', '初级', '否', 33.5, '17099887654', '1999-01-01',
            #                    '青峰白羽软件技术工作室',
            #                    '韩小顺', '电(高), 钳(中)']
            payment_amount = student.payment_amount
            if payment_amount == "0":
                payment_amount = ""
            elif payment_amount == 0:
                payment_amount = ""
            else:
                pass
            unpaid_amount = student.unpaid_amount
            if unpaid_amount == "0":
                unpaid_amount = ""
            elif unpaid_amount == 0:
                unpaid_amount = ""
            else:
                pass
            print(payment_amount)

            career_life = student.career_life
            original_certificate_worker_year = student.original_certificate_worker_year
            apprentice_year = student.apprentice_year
            apprentice_month = student.apprentice_month

            flag_working_time = False
            if student.identification_level == "3":
                working_year = ''
            elif student.identification_level == "4":
                if original_certificate_worker_year:
                    if original_certificate_worker_year > 0:
                        working_year = ''
                        flag_working_time = True
                    else:
                        flag_working_time = True
                else:
                    flag_working_time = True
            else:
                flag_working_time = True

            if flag_working_time:
                if not career_life:
                    if apprentice_year:
                        if apprentice_year > 0:
                            working_year = str(apprentice_year)
                        else:
                            if apprentice_month:
                                if apprentice_month > 0:
                                    working_year = str(apprentice_month) + "月"
                                else:
                                    working_year = ''
                    else:
                        working_year = ''
                else:
                    working_year = career_life
            else:
                pass
            
            # 文化程度
            education_degree = student.user_info.education_degree
            if education_degree:
                education_name = student.user_info.education_degree.education_name
            else:
                education_name = ''
            # 身份证住址
            rt_id_addr = RichText('')
            id_card_address = student.user_info.id_card_address
            if str(id_card_address).__len__() > 8:
                rt_id_addr.add(id_card_address, size=10)  # 字体大小
            elif str(id_card_address).__len__() > 13:
                rt_id_addr.add(id_card_address, size=8)  # 字体大小
            elif str(id_card_address).__len__() > 16:
                rt_id_addr.add(id_card_address, size=6)  # 字体大小
            else:
                rt_id_addr.add(id_card_address, size=14)  # 字体大小
            tmp_num = tmp_num + 1
            data.loc[tmp_num + 2] = [student.declaration_of_occupation,#职业工种
                                     identification_level,#级别
                                     '',#身份类型
                                     student.user_info.real_name,#中文名
                                     '',#英文名
                                     get_sex(student.user_info.sex),#性别
                                     student.user_info.birthday,#生日
                                     student.user_info.work_unit,#工作单位
                                     '',#从事职业
                                     student.user_info.nation_info.nation_name,#民族
                                     working_year,#工作年限
                                     education_name,#文化程度
                                     student.user_info.start_working_date,#参加工作日期
                                     '',#考生来源
                                     '',#现役军人
                                     '',#下岗人员
                                     '',#失业人员
                                     '',#残疾人员
                                     '',#农民工
                                     '',#两劳人员
                                     '',#其他
                                     '',#在校学生
                                     student.user_info.contact_number,#联系电话
                                     student.user_info.fixed_telephone,#手机
                                     rt_id_addr,#身份地址
                                     student.user_info.address,#常驻地址
                                     '',#邮政编码
                                     '',#政治面貌
                                     '',#报名点
                                     student.declaration_of_occupation,#鉴定科目
                                     '',#鉴定类型
                                     student.original_certificate_number,#原证书号
                                     '',#申报条件
                                     student.explain,#报名备注
                                     '',#补贴类型
                                     '',#补贴证件类型
                                     '',#补贴证件号码
                                     ''#预报考点
                                     ]
        return data
    else:
        pass
예제 #20
0
 def get_radiation(cif: CifContainer) -> RichText:
     rad_element, radtype, radline = format_radiation(cif['_diffrn_radiation_type'])
     radiation = RichText(rad_element)
     radiation.add(radtype, italic=True)
     radiation.add(radline, italic=True, subscript=True)
     return radiation
예제 #21
0
def spin_format(student_infos=None, skill_main_class_name=None, skill_main_class_code=None):
    """
    电子通信类
    :return:
    """
    try:
        document_root = os.path.join(BASE_DIR, 'document')
        filepath = document_root + "/spin_format_se.xlsx"

        # system_type = platform.system()
        # if 'indows' in system_type:
        #     filepath = "D:/PycharmProjects/lelingzdy/baoming/webapp/utils/fujian04_excel_format.xlsx"
        # else:
        #     filepath = "/opt/python3_space/lelingzdy/baoming/webapp/utils/fujian04_excel_format.xlsx"
        original_data = pd.read_excel(filepath, encoding='utf-8')
        # rb打开该excel,formatting_info=True表示打开excel时并保存原有的格式
        rb = xlrd.open_workbook(filepath, formatting_info=True)
        # 创建一个可写入的副本
        wb = xlutils.copy.copy(rb)
        if not student_infos:
            skill_main_classies = ReportSkillMainClass.objects.filter(skill_main_class_name__icontains='电子').\
                filter(skill_main_class_name__icontains='通信').values('id')
            if len(skill_main_classies) > 0:
                print(skill_main_classies[0])
                print(skill_main_classies[0]['id'])
                student_infos = StudentInfo.objects.filter(confirm_status=1, skill_main_class=skill_main_classies[0]['id'])
                # report_skills = ReportSkill.objects.filter(skill_main_class=skill_main_classies[0]).values('skill_id') 
                # if len(report_skills) > 0:
                #     report_conditions = ReportCondition.objects.filter(condition_for_skill__in=report_skills).values('condition_id')
                #     student_infos = StudentInfo.objects.filter(confirm_status=1, condition_selected__in=report_conditions)
                    # equipments = Equipment.objects.filter(rack__in = skill_main_classies)  
                    # student_infos = StudentInfo.objects.filter(confirm_status=1, chemical_worker=2)
        tmp_array = []
        if len(student_infos) > 0:
            tmp_num = 0
            for student in student_infos:
                identification_level = str(student.identification_level)
                if len(identification_level) > 0:
                    identification_level = worker_level[str(student.identification_level)]
                else:
                    identification_level = ''
                    # 原证书编号
                original_certificate_number = student.original_certificate_number
                if original_certificate_number:
                    pass
                else:
                    original_certificate_number = ""

                    # 文化程度
                education_degree = student.user_info.education_degree
                if education_degree:
                    education_name = student.user_info.education_degree.education_name
                else:
                    education_name = ''
                tmp_num = tmp_num + 1
                # tmp_dict = {'index': str(tmp_num),
                #             'r_e': student.user_info.real_name,
                #             'id_number': student.user_info.id_number,
                #             'sa': get_sex(student.user_info.sex),
                #             'school': student.user_info.middle_school,
                #             'f_occ': student.declaration_of_occupation,
                #             's_w_d': student.user_info.start_working_date,
                #             'id_level': identification_level,
                #             'jsll': '',
                #             'sjcz': '',
                #             'o_cer_num': original_certificate_number,
                #             'issuance_time': issuance_time}
                # tmp_list.append(tmp_dict)
                # 原级别
                primary_level = str(student.primary_level)
                if len(student.primary_level) > 0:
                    primary_level = worker_level[str(student.primary_level)]
                else:
                    primary_level = ''
                if student.user_info.start_working_date:
                    start_working_date = date_encoder(student.user_info.start_working_date)
                else:
                    start_working_date = ''

                if student.issuance_time:
                    issuance_time = date_encoder(student.issuance_time)
                else:
                    issuance_time = ''
                career_life = student.career_life
                original_certificate_worker_year = student.original_certificate_worker_year
                apprentice_year = student.apprentice_year
                apprentice_month = student.apprentice_month

                flag_working_time = False
                if student.identification_level == "3":
                    working_year = ''
                elif student.identification_level == "4":
                    if original_certificate_worker_year:
                        if original_certificate_worker_year > 0:
                            working_year = ''
                            flag_working_time = True
                        else:
                            flag_working_time = True
                    else:
                        flag_working_time = True
                else:
                    flag_working_time = True

                if flag_working_time:
                    if not career_life:
                        if apprentice_year:
                            if apprentice_year > 0:
                                working_year = str(apprentice_year)
                            else:
                                if apprentice_month:
                                    if apprentice_month > 0:
                                        working_year = str(apprentice_month) + "月"
                                    else:
                                        working_year = ''
                        else:
                            working_year = ''
                    else:
                        working_year = career_life
                else:
                    pass
                
                # 文化程度
                education_degree = student.user_info.education_degree
                if education_degree:
                    education_name = student.user_info.education_degree.education_name
                else:
                    education_name = ''
                # 身份证住址
                rt_id_addr = RichText('')
                id_card_address = student.user_info.id_card_address
                if str(id_card_address).__len__() > 8:
                    rt_id_addr.add(id_card_address, size=10)  # 字体大小
                elif str(id_card_address).__len__() > 13:
                    rt_id_addr.add(id_card_address, size=8)  # 字体大小
                elif str(id_card_address).__len__() > 16:
                    rt_id_addr.add(id_card_address, size=6)  # 字体大小
                else:
                    rt_id_addr.add(id_card_address, size=14)  # 字体大小
                tmp_array.append([tmp_num,
                                  student.user_info.real_name,#中文名
                                  get_sex(student.user_info.sex),#性别
                                  student.user_info.work_unit,#工作单位
                                  student.user_info.id_number,#身份证号
                                  education_name,#文化程度
                                  working_year,#工作年限
                                  identification_level,#级别
                                  student.declaration_of_occupation,#职业工种
                                  student.original_certificate_number,#原职业工种
                                  primary_level,#原职业等级
                                  ''#符合申报条件第多少项
                                ])
            num = 0
            if len(original_data) == 0:
                row_data = len(tmp_array)
            else:
                row_data = len(original_data)
            row_data += 3
            for row in range(0, row_data):
                print(row)
                print('第几行.....')
                if row > 2:
                    out_sheet = wb.get_sheet(0)
                    # row = row + 3
                    if num < len(tmp_array):
                        set_out_cell(out_sheet, 0, row, tmp_array[num][0])
                        set_out_cell(out_sheet, 1, row, tmp_array[num][1])
                        set_out_cell(out_sheet, 2, row, tmp_array[num][2])
                        set_out_cell(out_sheet, 3, row, tmp_array[num][3])
                        set_out_cell(out_sheet, 4, row, tmp_array[num][4])
                        set_out_cell(out_sheet, 5, row, tmp_array[num][5])
                        set_out_cell(out_sheet, 6, row, tmp_array[num][6])
                        set_out_cell(out_sheet, 7, row, tmp_array[num][7])
                        set_out_cell(out_sheet, 8, row, tmp_array[num][8])
                        set_out_cell(out_sheet, 9, row, tmp_array[num][9])
                        set_out_cell(out_sheet, 10, row, tmp_array[num][10])
                        set_out_cell(out_sheet, 11, row, tmp_array[num][11])
                    else:
                        set_out_cell(out_sheet, 0, row, num + 1)
                    num = num + 1

            day_string = str(time.strftime('%Y/%m/%d', time.localtime(time.time())))
            file_root = MEDIA_ROOT + "/files/"
            day_files_path = file_root + 'electronic_communication' + "/files/" + day_string
            if os.path.exists(day_files_path):
                pass
            else:
                os.makedirs(day_files_path)
            uuid_string = str(uuid.uuid4())
            file_day_files_path = day_files_path + "/" + uuid_string + ".xlsx"
            wb.save(file_day_files_path)            # 保存数据
            print("系统::" + file_day_files_path)

            if os.path.exists(file_day_files_path):
                file_manage = FileManage()
                file_manage.file_name = "电子通信模板-" + day_string
                file_manage.file_uuid = uuid_string
                file_manage.file_path = file_day_files_path
                file_manage.save()
                # 附件1 生成非化工类学员化名册成功,
                return str(file_manage.file_uuid)
            else:
                return None
        else:
            return None
    except Exception as e:
        print(e)
        raise e
예제 #22
0
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""RichText
"""

import docxtpl

from docxtpl import DocxTemplate
from docxtpl import RichText

tpl = DocxTemplate("./tmp.docx")

##define

rt = RichText("an example of")
rt.add('a rich text', style="myrichtextstyle")
rt.add('some violet', color="#ff00ff")

context = {"example": rt}

tpl.render(context)
tpl.save('./result.docx')
"""
某些内容在office中可以显示,在WPS中则无法显示,注意


注意,对于RichText内容,在模板中的变量前面需要写上一个r, {{r <var>}},注意r与花括号之间不能有空格;
如果没有r,在WPS中,无法显示RichText的内容
"""
def apply_chemical(student):
    """
    非化工类的申请表下载专用
    :param student:
    :return:
    """
    try:
        user_info = student.user_info
        document_root = os.path.join(BASE_DIR, 'document')
        tpl = DocxTemplate(document_root + '/fujian03.docx')
        # system_type = platform.system()
        # if 'indows' in system_type:
        #     tpl = DocxTemplate('D:/PycharmProjects/lelingzdy/baoming/webapp/utils/fujian03.docx')
        # else:
        #     tpl = DocxTemplate('/opt/python3_space/lelingzdy/baoming/webapp/utils/fujian03.docx')
        print(user_info.hukou_province.region_name)
        file_root = MEDIA_ROOT + '/' + str(
            user_info.two_inch_photo.picture_path)
        file_root = file_root.replace("\\", "/")
        id_number = str(user_info.id_number)
        rt_aa = RichText('')
        rt_aa.add(id_number[0], size=14)  # 字体大小
        rt_bb = RichText('')
        rt_bb.add(id_number[1], size=14)  # 字体大小
        rt_cc = RichText('')
        rt_cc.add(id_number[2], size=14)  # 字体大小
        rt_dd = RichText('')
        rt_dd.add(id_number[3], size=14)  # 字体大小
        rt_ee = RichText('')
        rt_ee.add(id_number[4], size=14)  # 字体大小
        rt_ff = RichText('')
        rt_ff.add(id_number[5], size=14)  # 字体大小
        rt_gg = RichText('')
        rt_gg.add(id_number[6], size=14)  # 字体大小
        rt_hh = RichText('')
        rt_hh.add(id_number[7], size=14)  # 字体大小
        rt_ii = RichText('')
        rt_ii.add(id_number[8], size=14)  # 字体大小
        rt_jj = RichText('')
        rt_jj.add(id_number[9], size=14)  # 字体大小
        rt_kk = RichText('')
        rt_kk.add(id_number[10], size=14)  # 字体大小
        rt_ll = RichText('')
        rt_ll.add(id_number[11], size=14)  # 字体大小
        rt_mm = RichText('')
        rt_mm.add(id_number[12], size=14)  # 字体大小
        rt_nn = RichText('')
        rt_nn.add(id_number[13], size=14)  # 字体大小
        rt_oo = RichText('')
        rt_oo.add(id_number[14], size=14)  # 字体大小
        rt_pp = RichText('')
        rt_pp.add(id_number[15], size=14)  # 字体大小
        rt_qq = RichText('')
        rt_qq.add(id_number[16], size=14)  # 字体大小
        rt_rr = RichText('')
        rt_rr.add(id_number[17], size=14)  # 字体大小

        # 户口所在地
        rt_hukou = RichText('')
        hukou = user_info.hukou_province.region_name + user_info.hukou_city.region_name + user_info.hukou_county.region_name
        if str(hukou).__len__() > 8:
            rt_hukou.add(hukou, size=10)  # 字体大小
        elif str(hukou).__len__() > 13:
            rt_hukou.add(hukou, size=8)  # 字体大小
        else:
            rt_hukou.add(hukou, size=14)  # 字体大小

        # 身份证住址
        rt_id_addr = RichText('')
        id_card_address = user_info.id_card_address
        if str(id_card_address).__len__() > 8:
            rt_id_addr.add(id_card_address, size=10)  # 字体大小
        elif str(id_card_address).__len__() > 13:
            rt_id_addr.add(id_card_address, size=8)  # 字体大小
        elif str(id_card_address).__len__() > 16:
            rt_id_addr.add(id_card_address, size=6)  # 字体大小
        else:
            rt_id_addr.add(id_card_address, size=14)  # 字体大小

        # 政治面貌
        rt_p_status = RichText('')
        political_status_value = political_status[str(
            user_info.political_status)]
        # rt_p_status.add(political_status_value, size=12)  # 字体大小
        if str(political_status_value).__len__() >= 4:
            rt_p_status.add(political_status_value, size=14)  # 字体大小
        else:
            rt_p_status.add(political_status_value)  # 字体大小

        # 原职业工种
        rt_former_occupation = RichText('')
        former_occupation = student.former_occupation
        if str(former_occupation).__len__() >= 4:
            rt_former_occupation.add(former_occupation, size=14)  # 字体大小
        else:
            rt_former_occupation.add(former_occupation)  # 字体大小
        # 申报职业
        rt_declaration_of_occupation = RichText('')
        declaration_of_occupation = student.declaration_of_occupation
        if str(declaration_of_occupation).__len__() >= 4:
            rt_declaration_of_occupation.add(declaration_of_occupation,
                                             size=14)  # 字体大小
        else:
            rt_declaration_of_occupation.add(declaration_of_occupation)  # 字体大小

            # 原级别
        primary_level = str(student.primary_level)
        if len(student.primary_level) > 0:
            primary_level = worker_level[str(student.primary_level)]
        else:
            primary_level = ''

        # 申报级别
        identification_level = str(student.identification_level)
        if len(identification_level) > 0:
            identification_level = worker_level[str(
                student.identification_level)]
        else:
            identification_level = ''
        # 原证书编号
        original_certificate_number = student.original_certificate_number
        if original_certificate_number:
            pass
        else:
            original_certificate_number = ""

        if student.issuance_time:
            issuance_time = student.issuance_time
        else:
            issuance_time = ''

        career_life = student.career_life
        original_certificate_worker_year = student.original_certificate_worker_year
        apprentice_year = student.apprentice_year
        apprentice_month = student.apprentice_month

        flag_working_time = False
        if student.identification_level == "3":
            working_year = ''
        elif student.identification_level == "4":
            if original_certificate_worker_year:
                if original_certificate_worker_year > 0:
                    working_year = ''
                else:
                    flag_working_time = True
            else:
                flag_working_time = True
        else:
            flag_working_time = True

        if flag_working_time:
            if not career_life:
                if apprentice_year:
                    if apprentice_year > 0:
                        working_year = str(apprentice_year)
                    else:
                        if apprentice_month:
                            if apprentice_month > 0:
                                working_year = str(apprentice_month) + "月"
                            else:
                                working_year = ''
                else:
                    working_year = ''
            else:
                working_year = career_life
        else:
            pass

        # if not career_life:
        #     if original_certificate_worker_year:
        #         working_year = original_certificate_worker_year
        #     else:
        #         if apprentice_year > 0:
        #             working_year = str(apprentice_year)
        #         else:
        #             if apprentice_month > 0:
        #                 working_year = str(apprentice_month) + "月"
        #             else:
        #                 working_year = ''
        # else:
        #     working_year = career_life
        #
        # if student.identification_level == "3":
        #     working_year = ''
        #
        # if student.identification_level == "4":
        #     if original_certificate_worker_year > 0:
        #         working_year = ''
        #
        # if working_year is None:
        #     working_year = ''

        # 文化程度
        education_degree = student.user_info.education_degree
        if education_degree:
            education_name = student.user_info.education_degree.education_name
        else:
            education_name = ''
        context = {
            'r_e': user_info.real_name,
            'sa': get_sex(user_info.sex),
            'bir': user_info.birthday,
            'edu': education_name,
            'id_number': user_info.id_number,
            'work_unit': user_info.work_unit,
            'u_n': user_info.unit_nature.unit_nature,
            's_w_d': user_info.start_working_date,
            'cl': working_year,
            'hukou': rt_hukou,
            'email': user_info.email,
            'f_p': user_info.fixed_telephone,
            'unit_address': user_info.unit_address,
            'address': user_info.address,
            'id_addr': rt_id_addr,
            'postal_c': user_info.postal_code,
            # 'p': rt_p_status,
            'nati': user_info.nation_info.nation_name,
            'f_occ': rt_former_occupation,
            'p_level': primary_level,
            'issuance_time': issuance_time,
            'issue_unit': student.issue_unit,
            'o_cer_num': original_certificate_number,
            'dec_of_occ': rt_declaration_of_occupation,
            'id_level': identification_level,
            'work_training': student.work_training,
            'inch_img': InlineImage(tpl,
                                    file_root,
                                    width=Mm(35),
                                    height=Mm(48)),
            'major': student.major,
            'a': rt_aa,
            'b': rt_bb,
            'c': rt_cc,
            'd': rt_dd,
            'e': rt_ee,
            'f': rt_ff,
            'g': rt_gg,
            'h': rt_hh,
            'i': rt_ii,
            'j': rt_jj,
            'k': rt_kk,
            'l': rt_ll,
            'm': rt_mm,
            'n': rt_nn,
            'o': rt_oo,
            'p': rt_pp,
            'q': rt_qq,
            'r': rt_rr
        }
        day_string = str(time.strftime('%Y/%m/%d',
                                       time.localtime(time.time())))
        file_root = MEDIA_ROOT + "/files/"
        day_files_path = file_root + 'report_files/apply_chemical/' + student.declaration_of_occupation + "/" + str(
            student.identification_level) + "/" + day_string
        if os.path.exists(day_files_path):
            pass
        else:
            os.makedirs(day_files_path)
        uuid_string = str(uuid.uuid4())
        file_day_files_path = day_files_path + "/" + uuid_string + ".docx"
        jinja_env = jinja2.Environment(autoescape=True)
        tpl.render(context, jinja_env)
        tpl.save(file_day_files_path)
        if os.path.exists(file_day_files_path):
            file_manage = FileManage()
            file_manage.file_name = "化工报表-" + declaration_of_occupation
            file_manage.file_uuid = uuid_string
            file_manage.file_path = file_day_files_path
            file_manage.save()
            # 附件1 申请表获取成功,

            return str(file_manage.file_uuid)
        else:
            return None
    except Exception as e:
        print(e)
        raise e
예제 #24
0
# template = env.get_template('hello_world.txt')

# content = {'name': 'Yoni', 'lastname': 'gg'}
# output = template.render(data=content)
# print(output)

################## example 2 #############################

doc = DocxTemplate("Fishman_Daily_Check_FORMAT.docx")
# Where the magic happens

rt = RichText()

# rt.add("\u2713", color='#008000')
rt.add("\u2717", color='#FF0000')
context = {
    "current_date": "01/01/20",
    "DC2008": rt,
    "MEGA_PDC": rt,
    "Newdc": rt,
    "Cluster": rt,
    "ESXi01": rt,
    "ESXi02": rt,
    "ESXi03": rt,
    "ESXi04": rt,
    "ESXi05": rt,
    "ESXi06": rt,
    "Datastore2": rt,
    "Datastore3": rt,
    "Datastore4": rt,
예제 #25
0
def getMean(normal, tumor):
    mean = RichText('注:人群的HLA-I分型存在广泛的多态性,本报告所列举的HLA-I分型结果由基因测序获得')
    B62 = ['B*15:02', 'B*15:12', 'B*15:13', 'B*46:01', 'B*52:01']
    B44 = [
        'B*18:01', 'B*37:01', 'B*40:01', 'B*40:02', 'B*40:06', 'B*44:02',
        'B*44:03', 'B*45:01'
    ]
    PD1 = ['B*15:01'] + B62 + B44
    ####
    if getHeterozy(normal['A']) == 'heterozy' and getHeterozy(
            normal['B']) == 'heterozy' and getHeterozy(
                normal['C']) == 'heterozy':
        mean.add(
            '\n*本次检测从正常体细胞检测到所有的等位基因都处于杂合状态,最新研究显示相较于至少一个位置的等位基因为纯合状态的患者,全部为杂合状态的患者在接受anti-PD-1药物治疗时生存期中位数更长(Chowell '
        )
        mean.add('et al., Science)', italic=True)
        if getHeterozy(tumor['A']) == 'heterozy' and getHeterozy(
                tumor['B']) == 'heterozy' and getHeterozy(
                    tumor['C']) == 'heterozy':
            mean.add(
                '\n*40%的非小细胞肺癌患者的肿瘤样本中检测到HLA-I的杂合性缺失,这与亚克隆的新抗原负载高相关(McGranahan '
            )
            mean.add('et al., Cell', italic=True)
            mean.add('),而本次检测未发现肿瘤样本和正常体细胞中存在HLA-I的分型差异')
    if getHeterozy(normal['A']) == 'isozy' or getHeterozy(
            normal['B']) == 'isozy' or getHeterozy(normal['C']) == 'isozy':
        mean.add(
            '\n*本次检测从正常细胞中检测到存在至少一个等位基因为纯合状态,根据最新研究显示相较于所有等位基因都处于杂合状态的患者,至少一个等位基因为纯合状态的患者在接受anti-PD-1药物治疗时生存期中位数较短(Chowell '
        )
        mean.add('et al., Science)', italic=True)
    ###
    if len(set(normal['B'])
           & set(B62)) > 0 and len(set(tumor['B']) & set(B62)) > 0:
        mean.add(
            '\n*最新研究显示携带有HLA-B62 supertype的等位基因的患者接受anti-PD-1治疗的预后较差(Chowell ')
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从正常细胞和肿瘤组织中都检测到HLA-B62 supertype中的等位基因')
    elif len(set(normal['B'])
             & set(B62)) == 0 and len(set(tumor['B']) & set(B62)) > 0:
        mean.add(
            '\n*最新研究显示携带有HLA-B62 supertype的等位基因的患者接受anti-PD-1治疗的预后较差(Chowell ')
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从肿瘤组织中检测到HLA-B62 supertype中的等位基因')
    elif len(set(normal['B'])
             & set(B62)) > 0 and len(set(tumor['B']) & set(B62)) == 0:
        mean.add(
            '\n*最新研究显示携带有HLA-B62 supertype的等位基因的患者接受anti-PD-1治疗的预后较差(Chowell ')
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从正常细胞中检测到HLA-B62 supertype中的等位基因')
    ###
    if 'B*15:01' in normal['B'] and 'B*15:01' in tumor['B']:
        mean.add(
            '\n*最新研究显示携带有HLA-B62 supertype的B*15:01等位基因的患者接受anti-PD-1治疗的预后较差,这可能是因为B*15:01 的分子结构会影响T细胞对肿瘤细胞的识别能力(Chowell '
        )
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从正常组织和肿瘤组织中都检测到B*15:01')
    elif not 'B*15:01' in normal['B'] and 'B*15:01' in tumor['B']:
        mean.add(
            '\n*最新研究显示携带有HLA-B62 supertype的B*15:01等位基因的患者接受anti-PD-1治疗的预后较差,这可能是因为B*15:01 的分子结构会影响T细胞对肿瘤细胞的识别能力(Chowell '
        )
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从肿瘤组织中检测到B*15:01')
    elif 'B*15:01' in normal['B'] and not 'B*15:01' in tumor['B']:
        mean.add(
            '\n*最新研究显示携带有HLA-B62 supertype的B*15:01等位基因的患者接受anti-PD-1治疗的预后较差,这可能是因为B*15:01 的分子结构会影响T细胞对肿瘤细胞的识别能力(Chowell '
        )
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从正常细胞中检测到B*15:01')
    ###
    if len(set(normal['B'])
           & set(B44)) > 0 and len(set(tumor['B']) & set(B44)) > 0:
        mean.add(
            '\n*最新研究显示携带有HLA-B44 supertype的等位基因的患者接受anti-PD-1治疗的生存期中位数更长(Chowell '
        )
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从正常细胞和肿瘤组织中都检测到HLA-B44 supertype中的等位基因')
    elif len(set(normal['B'])
             & set(B44)) == 0 and len(set(tumor['B']) & set(B44)) > 0:
        mean.add(
            '\n*最新研究显示携带有HLA-B44 supertype的等位基因的患者接受anti-PD-1治疗的生存期中位数更长(Chowell '
        )
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从肿瘤组织中检测到HLA-B44 supertype中的等位基因')
    elif len(set(normal['B'])
             & set(B44)) > 0 and len(set(tumor['B']) & set(B44)) > 0:
        mean.add(
            '\n*最新研究显示携带有HLA-B44 supertype的等位基因的患者接受anti-PD-1治疗的生存期中位数更长(Chowell '
        )
        mean.add('et al., Science', italic=True)
        mean.add('),本次检测从正常细胞中检测到HLA-B44 supertype中的等位基因')
    #####
    if len(set(normal['B'])
           & set(PD1)) == 0 and len(set(tumor['B']) & set(PD1)) == 0:
        mean.add('\n*本次检测未发现任何已知的影响anti-PD-1治疗预后的HLA等位基因')
    ###
    #mean='\n'.join(mean)
    return mean
예제 #26
0
def generateRichText2(doc, raw_html, DC_STYLE):
    listePropre = decoupe_html (raw_html)
    rt = RichText(style=DC_STYLE)
    for elt in listePropre:
        #Gestion des paragraphes
        if type(elt) == type('une string'):
            if listePropre.index(elt) == 0:
                rt.add(elt+'\n')
            else:
                text='\a'+elt+'\n'
                rt.add(text)
        #Gestion des listes
        elif type(elt) == list:
            ul=elt
            #parcours des elements de la liste ul
            for elt in ul:
                for li in elt:
                    #niv 1
                    if type(li) == type('une string'):
                        rt.add("• "+li+"\n")
                    #sinon
                    elif type(li) == list:
                        for subul in li:
                            for subli in subul:
                                #niv 2
                                if type(subli) == type('une string'):
                                    rt.add("\t"+"○ "+subli+"\n")
                                #sinon
                                elif type(subli) == list:
                                    for subsubul in subli:
                                        for subsubli in subsubul:
                                            #niv 3
                                            if type(subsubli) == type('une string'):
                                                rt.add("\t\t"+"◙ "+subsubli+"\n")
                                            #sinon
                                            elif type(subsubli) == list:
                                                for subsubsubul in subsubli:
                                                    for subsubsubli in subsubsubul:
                                                        #niv4
                                                        if type(subsubsubli) == type('une string'):
                                                            rt.add("\t\t\t"+"■ "+subsubsubli+"\n")
                                                
    return(rt)
def electronic_communication_format(student_infos=None,
                                    skill_main_class_name=None,
                                    skill_main_class_code=None):
    """
    电子通信类
    :return:
    """
    try:
        document_root = os.path.join(BASE_DIR, 'document')
        filepath = document_root + "/electronic_communication_format.xlsx"

        # system_type = platform.system()
        # if 'indows' in system_type:
        #     filepath = "D:/PycharmProjects/lelingzdy/baoming/webapp/utils/fujian04_excel_format.xlsx"
        # else:
        #     filepath = "/opt/python3_space/lelingzdy/baoming/webapp/utils/fujian04_excel_format.xlsx"
        original_data = pd.read_excel(filepath, encoding='utf-8')
        # rb打开该excel,formatting_info=True表示打开excel时并保存原有的格式
        rb = xlrd.open_workbook(filepath, formatting_info=True)
        # 创建一个可写入的副本
        wb = xlutils.copy.copy(rb)
        if not student_infos:
            skill_main_classies = ReportSkillMainClass.objects.filter(skill_main_class_name__icontains='电子').\
                filter(skill_main_class_name__icontains='通信').values('id')
            if len(skill_main_classies) > 0:
                print(skill_main_classies[0])
                print(skill_main_classies[0]['id'])
                student_infos = StudentInfo.objects.filter(
                    confirm_status=1,
                    skill_main_class=skill_main_classies[0]['id'])
                # report_skills = ReportSkill.objects.filter(skill_main_class=skill_main_classies[0]).values('skill_id')
                # if len(report_skills) > 0:
                #     report_conditions = ReportCondition.objects.filter(condition_for_skill__in=report_skills).values('condition_id')
                #     student_infos = StudentInfo.objects.filter(confirm_status=1, condition_selected__in=report_conditions)
                # equipments = Equipment.objects.filter(rack__in = skill_main_classies)
                # student_infos = StudentInfo.objects.filter(confirm_status=1, chemical_worker=2)
        tmp_array = []
        if len(student_infos) > 0:
            tmp_num = 0
            for student in student_infos:
                identification_level = str(student.identification_level)
                if len(identification_level) > 0:
                    identification_level = worker_level[str(
                        student.identification_level)]
                else:
                    identification_level = ''
                    # 原证书编号
                original_certificate_number = student.original_certificate_number
                if original_certificate_number:
                    pass
                else:
                    original_certificate_number = ""

                    # 文化程度
                education_degree = student.user_info.education_degree
                if education_degree:
                    education_name = student.user_info.education_degree.education_name
                else:
                    education_name = ''
                tmp_num = tmp_num + 1
                # tmp_dict = {'index': str(tmp_num),
                #             'r_e': student.user_info.real_name,
                #             'id_number': student.user_info.id_number,
                #             'sa': get_sex(student.user_info.sex),
                #             'school': student.user_info.middle_school,
                #             'f_occ': student.declaration_of_occupation,
                #             's_w_d': student.user_info.start_working_date,
                #             'id_level': identification_level,
                #             'jsll': '',
                #             'sjcz': '',
                #             'o_cer_num': original_certificate_number,
                #             'issuance_time': issuance_time}
                # tmp_list.append(tmp_dict)
                # 原级别
                primary_level = str(student.primary_level)
                if len(student.primary_level) > 0:
                    primary_level = worker_level[str(student.primary_level)]
                else:
                    primary_level = ''
                if student.user_info.start_working_date:
                    start_working_date = date_encoder(
                        student.user_info.start_working_date)
                else:
                    start_working_date = ''

                if student.issuance_time:
                    issuance_time = date_encoder(student.issuance_time)
                else:
                    issuance_time = ''
                career_life = student.career_life
                original_certificate_worker_year = student.original_certificate_worker_year
                apprentice_year = student.apprentice_year
                apprentice_month = student.apprentice_month

                flag_working_time = False
                if student.identification_level == "3":
                    working_year = ''
                elif student.identification_level == "4":
                    if original_certificate_worker_year:
                        if original_certificate_worker_year > 0:
                            working_year = ''
                            flag_working_time = True
                        else:
                            flag_working_time = True
                    else:
                        flag_working_time = True
                else:
                    flag_working_time = True

                if flag_working_time:
                    if not career_life:
                        if apprentice_year:
                            if apprentice_year > 0:
                                working_year = str(apprentice_year)
                            else:
                                if apprentice_month:
                                    if apprentice_month > 0:
                                        working_year = str(
                                            apprentice_month) + "月"
                                    else:
                                        working_year = ''
                        else:
                            working_year = ''
                    else:
                        working_year = career_life
                else:
                    pass

                # 文化程度
                education_degree = student.user_info.education_degree
                if education_degree:
                    education_name = student.user_info.education_degree.education_name
                else:
                    education_name = ''
                # 身份证住址
                rt_id_addr = RichText('')
                id_card_address = student.user_info.id_card_address
                if str(id_card_address).__len__() > 8:
                    rt_id_addr.add(id_card_address, size=10)  # 字体大小
                elif str(id_card_address).__len__() > 13:
                    rt_id_addr.add(id_card_address, size=8)  # 字体大小
                elif str(id_card_address).__len__() > 16:
                    rt_id_addr.add(id_card_address, size=6)  # 字体大小
                else:
                    rt_id_addr.add(id_card_address, size=14)  # 字体大小
                tmp_array.append([
                    student.declaration_of_occupation,  #职业工种
                    identification_level,  #级别
                    '',  #身份类型
                    '',  #证件号码
                    student.user_info.real_name,  #中文名
                    '',  #英文名
                    get_sex(student.user_info.sex),  #性别
                    student.user_info.birthday,  #生日
                    student.user_info.work_unit,  #工作单位
                    '',  #从事职业
                    student.user_info.nation_info.nation_name,  #民族
                    str(working_year) + '年',  #工作年限
                    education_name,  #文化程度
                    student.user_info.start_working_date,  #参加工作日期
                    '',  #考生来源
                    '',  #来源省份
                    '',  #来源地区
                    '',  #现役军人
                    '',  #下岗人员
                    '',  #失业人员
                    '',  #残疾人员
                    '',  #农民工
                    '',  #两劳人员
                    '',  #其他
                    '',  #在校学生
                    student.user_info.contact_number,  #联系电话
                    student.user_info.fixed_telephone,  #手机
                    student.user_info.id_card_address,  #身份地址
                    student.user_info.address,  #常驻地址
                    '',  #邮政编码
                    '',  #政治面貌
                    '',  #报名点
                    student.declaration_of_occupation,  #鉴定科目
                    '',  #鉴定类型
                    student.original_certificate_number,  #原证书号
                    '',  #申报条件
                    student.explain,  #报名备注
                    '',  #补贴类型
                    '',  #补贴证件类型
                    '',  #补贴证件号码
                    ''  #预报考点
                ])
            num = 0
            if len(original_data) == 0:
                row_data = len(tmp_array)
            else:
                row_data = len(original_data)
            for row in range(0, row_data):
                print(row)
                print('第几行.....')
                # if row > 0:
                out_sheet = wb.get_sheet(0)
                row = row + 1
                if num < len(tmp_array):
                    set_out_cell(out_sheet, 0, row, tmp_array[num][0])
                    set_out_cell(out_sheet, 1, row, tmp_array[num][1])
                    set_out_cell(out_sheet, 2, row, tmp_array[num][2])
                    set_out_cell(out_sheet, 3, row, tmp_array[num][3])
                    set_out_cell(out_sheet, 4, row, tmp_array[num][4])
                    set_out_cell(out_sheet, 5, row, tmp_array[num][5])
                    set_out_cell(out_sheet, 6, row, tmp_array[num][6])
                    set_out_cell(out_sheet, 7, row, tmp_array[num][7])
                    set_out_cell(out_sheet, 8, row, tmp_array[num][8])
                    set_out_cell(out_sheet, 9, row, tmp_array[num][9])
                    set_out_cell(out_sheet, 10, row, tmp_array[num][10])
                    set_out_cell(out_sheet, 11, row, tmp_array[num][11])
                    set_out_cell(out_sheet, 12, row, tmp_array[num][12])
                    set_out_cell(out_sheet, 13, row, tmp_array[num][13])
                    set_out_cell(out_sheet, 14, row, tmp_array[num][14])
                    set_out_cell(out_sheet, 15, row, tmp_array[num][15])
                    set_out_cell(out_sheet, 16, row, tmp_array[num][16])
                    set_out_cell(out_sheet, 17, row, tmp_array[num][17])
                    set_out_cell(out_sheet, 18, row, tmp_array[num][18])
                    set_out_cell(out_sheet, 19, row, tmp_array[num][19])
                    set_out_cell(out_sheet, 20, row, tmp_array[num][20])
                    set_out_cell(out_sheet, 21, row, tmp_array[num][21])
                    set_out_cell(out_sheet, 22, row, tmp_array[num][22])
                    set_out_cell(out_sheet, 23, row, tmp_array[num][23])
                    set_out_cell(out_sheet, 24, row, tmp_array[num][24])
                    set_out_cell(out_sheet, 25, row, tmp_array[num][25])
                    set_out_cell(out_sheet, 26, row, tmp_array[num][26])
                    set_out_cell(out_sheet, 27, row, tmp_array[num][27])
                    set_out_cell(out_sheet, 28, row, tmp_array[num][28])
                    set_out_cell(out_sheet, 29, row, tmp_array[num][29])
                    set_out_cell(out_sheet, 30, row, tmp_array[num][30])
                    set_out_cell(out_sheet, 31, row, tmp_array[num][31])
                    set_out_cell(out_sheet, 32, row, tmp_array[num][32])
                    set_out_cell(out_sheet, 33, row, tmp_array[num][33])
                    set_out_cell(out_sheet, 34, row, tmp_array[num][34])
                    set_out_cell(out_sheet, 35, row, tmp_array[num][35])
                    set_out_cell(out_sheet, 36, row, tmp_array[num][36])
                    set_out_cell(out_sheet, 37, row, tmp_array[num][37])
                    set_out_cell(out_sheet, 38, row, tmp_array[num][38])
                    set_out_cell(out_sheet, 39, row, tmp_array[num][39])
                else:
                    set_out_cell(out_sheet, 0, row, num + 1)
                num = num + 1

            day_string = str(
                time.strftime('%Y/%m/%d', time.localtime(time.time())))
            file_root = MEDIA_ROOT + "/files/"
            day_files_path = file_root + 'electronic_communication' + "/files/" + day_string
            if os.path.exists(day_files_path):
                pass
            else:
                os.makedirs(day_files_path)
            uuid_string = str(uuid.uuid4())
            file_day_files_path = day_files_path + "/" + uuid_string + ".xlsx"
            wb.save(file_day_files_path)  # 保存数据
            print("系统::" + file_day_files_path)

            if os.path.exists(file_day_files_path):
                file_manage = FileManage()
                file_manage.file_name = "电子通信模板-" + day_string
                file_manage.file_uuid = uuid_string
                file_manage.file_path = file_day_files_path
                file_manage.save()
                # 附件1 生成非化工类学员化名册成功,
                return str(file_manage.file_uuid)
            else:
                return None
        else:
            return None
    except Exception as e:
        print(e)
        raise e
예제 #28
0
# -*- coding: utf-8 -*-
'''
Created : 2015-03-26

@author: Eric Lapouyade
'''

from docxtpl import DocxTemplate, RichText

tpl = DocxTemplate('templates/richtext_tpl.docx')

rt = RichText()
rt.add('a rich text', style='myrichtextstyle')
rt.add(' with ')
rt.add('some italic', italic=True)
rt.add(' and ')
rt.add('some violet', color='#ff00ff')
rt.add(' and ')
rt.add('some striked', strike=True)
rt.add(' and ')
rt.add('some small', size=14)
rt.add(' or ')
rt.add('big', size=60)
rt.add(' text.')
rt.add('\nYou can add an hyperlink, here to ')
rt.add('google', url_id=tpl.build_url_id('http://google.com'))
rt.add('\nEt voilà ! ')
rt.add('\n1st line')
rt.add('\n2nd line')
rt.add('\n3rd line')
rt.add('\n\n<cool>')
예제 #29
0
def apply_electronic_communiction(student):
    """
    电子行业的申请表下载专用
    :param student:
    :return:
    """
    try:
        user_info = student.user_info
        print(user_info.real_name)

        document_root = os.path.join(BASE_DIR, 'document')
        tpl = DocxTemplate(document_root + '/electronic_communication.docx')
        # print(user_info.hukou_province.region_name)
        file_root = MEDIA_ROOT + '/' + str(user_info.two_inch_photo.picture_path)
        file_root = file_root.replace("\\", "/")

        # 户口所在地
        rt_hukou = RichText('')
        hukou = user_info.hukou_province.region_name + user_info.hukou_city.region_name + user_info.hukou_county.region_name
        if str(hukou).__len__() > 8:
            rt_hukou.add(hukou, size=10)  # 字体大小
        elif str(hukou).__len__() > 13:
            rt_hukou.add(hukou, size=8)  # 字体大小
        else:
            rt_hukou.add(hukou, size=14)  # 字体大小

        # 身份证住址
        rt_id_addr = RichText('')
        id_card_address = user_info.id_card_address
        if str(id_card_address).__len__() > 8:
            rt_id_addr.add(id_card_address, size=10)  # 字体大小
        elif str(id_card_address).__len__() > 13:
            rt_id_addr.add(id_card_address, size=8)  # 字体大小
        elif str(id_card_address).__len__() > 16:
            rt_id_addr.add(id_card_address, size=6)  # 字体大小
        else:
            rt_id_addr.add(id_card_address, size=14)  # 字体大小

        # 政治面貌
        rt_p_status = RichText('')
        political_status_value = political_status[str(user_info.political_status)]
        # rt_p_status.add(political_status_value, size=12)  # 字体大小
        if str(political_status_value).__len__() >= 4:
            rt_p_status.add(political_status_value, size=14)  # 字体大小
        else:
            rt_p_status.add(political_status_value)  # 字体大小

        # 原职业工种
        rt_former_occupation = RichText('')
        former_occupation = student.former_occupation
        if former_occupation:
            if str(former_occupation).__len__() >= 4:
                rt_former_occupation.add(former_occupation, size=14)  # 字体大小
            else:
                rt_former_occupation.add(former_occupation)  # 字体大小
        else:
            rt_former_occupation.add('')
        # 申报职业
        rt_declaration_of_occupation = RichText('')
        declaration_of_occupation = student.declaration_of_occupation
        if str(declaration_of_occupation).__len__() >= 4:
            rt_declaration_of_occupation.add(declaration_of_occupation, size=14)  # 字体大小
        else:
            rt_declaration_of_occupation.add(declaration_of_occupation)  # 字体大小

        # 原级别
        primary_level = str(student.primary_level)
        if len(student.primary_level) > 0:
            primary_level = worker_level[str(student.primary_level)]
        else:
            primary_level = ''

        # 申报级别
        identification_level = str(student.identification_level)
        if len(identification_level) > 0:
            identification_level = worker_level[str(student.identification_level)]
        else:
            identification_level = ''

        # 文化程度
        education_degree = student.user_info.education_degree
        if education_degree:
            education_name = student.user_info.education_degree.education_name
        else:
            education_name = ''

        # career_life = student.career_life
        # original_certificate_worker_year = student.original_certificate_worker_year
        # print("career_life::" + str(career_life))
        # print("original_certificate_worker_year::" + str(original_certificate_worker_year))
        # 
        # working_year = None
        # if not career_life:
        #     if original_certificate_worker_year:
        #         working_year = original_certificate_worker_year
        # else:
        #     working_year = career_life
        # 
        # if working_year is None:
        #     working_year = ''
        
        # 修改的内容
        career_life = student.career_life
        original_certificate_worker_year = student.original_certificate_worker_year
        apprentice_year = student.apprentice_year
        apprentice_month = student.apprentice_month

        flag_working_time = False
        if student.identification_level == "3":
            working_year = ''
        elif student.identification_level == "4":
            if original_certificate_worker_year:
                if original_certificate_worker_year > 0:
                    working_year = ''
                    flag_working_time = True
                else:
                    flag_working_time = True
            else:
                flag_working_time = True
        else:
            flag_working_time = True

        if flag_working_time:
            if not career_life:
                if apprentice_year:
                    if apprentice_year > 0:
                        working_year = str(apprentice_year)
                    else:
                        if apprentice_month:
                            if apprentice_month > 0:
                                working_year = str(apprentice_month) + "月"
                            else:
                                working_year = ''
                else:
                    working_year = ''
            else:
                working_year = career_life
        else:
            pass
        
        # 修改的内容
        print('working_year::' + str(working_year))

        print("user_info.real_name:::" + user_info.real_name)
        context = {
            'r_e': user_info.real_name,
            'sa': get_sex(user_info.sex),
            'bir': user_info.birthday,
            'edu': education_name,
            'id_number': user_info.id_number,
            'work_unit': user_info.work_unit,
            'u_n': user_info.unit_nature.unit_nature,
            's_w_d': user_info.start_working_date,
            'cl': working_year,
            'hukou': rt_hukou,
            'email': user_info.email,
            'f_p': user_info.fixed_telephone,
            'unit_address': user_info.unit_address,
            'address': user_info.address,
            'id_addr': rt_id_addr,
            'postal_c': user_info.postal_code,
            'p': rt_p_status,
            'nation': user_info.nation_info.nation_name,
            'f_occ': rt_former_occupation,
            'p_level': primary_level,
            'o_cer_num': student.original_certificate_number,
            'main_occupation': student.user_info.main_occupation,
            'dec_of_occ': rt_declaration_of_occupation,
            'id_level': identification_level,
            'work_training': student.work_training,
            'inch_img': InlineImage(tpl, file_root, width=Mm(35), height=Mm(48))
        }
        day_string = str(time.strftime('%Y/%m/%d', time.localtime(time.time())))
        # day_files_path = 'django/apply_not_chemical' + "/files/" + day_string
        file_root = MEDIA_ROOT + "/files/"
        day_files_path = file_root + 'report_files/apply_electronic_communication/' + student.declaration_of_occupation + "/" + str(
            student.identification_level) + "/" + day_string
        if os.path.exists(day_files_path):
            pass
        else:
            os.makedirs(day_files_path)

        file_manage = FileManage()
        jinja_env = jinja2.Environment(autoescape=True)
        # 将附件 1 保存到文件系统
        uuid_string = str(uuid.uuid4())
        file_day_files_path = day_files_path + "/" + uuid_string + ".docx"
        tpl.render(context, jinja_env)
        tpl.save(file_day_files_path)
        if os.path.exists(file_day_files_path):
            file_manage.file_name = "非化工类报表-" + declaration_of_occupation
            file_manage.file_uuid = uuid_string
            file_manage.file_path = file_day_files_path
            file_manage.save()
        else:
            pass

        return str(uuid_string)
    except Exception as e:
        print(e)
        raise e
예제 #30
0
# -*- coding: utf-8 -*-
'''
Created : 2015-03-26

@author: Eric Lapouyade
'''

from docxtpl import DocxTemplate, RichText

tpl = DocxTemplate('test_files/richtext_tpl.docx')

rt = RichText('an exemple of ')
rt.add('a rich text', style='myrichtextstyle')
rt.add(' with ')
rt.add('some italic', italic=True)
rt.add(' and ')
rt.add('some violet', color='#ff00ff')
rt.add(' and ')
rt.add('some striked', strike=True)
rt.add(' and ')
rt.add('some small', size=14)
rt.add(' or ')
rt.add('big', size=60)
rt.add(' text.')
rt.add(' Et voilà ! ')
rt.add('\n1st line')
rt.add('\n2nd line')
rt.add('\n3rd line')
rt.add('\n\n<cool>')

context = {
예제 #31
0
def generate_detailed_report(project, outputname, sqc):
    doc = None

    print "> Calculating language metrics..."
    ncloc = sqc.get_loc(project[1]["key"])
    languages = sqc.get_loc_lang_metrics(project[1]["key"], ncloc)
    ncloc = resources.span_number_format(int(ncloc))

    print "> Retrieving issues..."
    vulnerabilities_num = sqc.get_issues_on_type(
        "VULNERABILITY,SECURITY_HOTSPOT", project[1]["key"])
    vulnerabilities = resources.span_number_format(int(vulnerabilities_num))
    bugs_num = sqc.get_issues_on_type("BUG", project[1]["key"])
    bugs = resources.span_number_format(int(bugs_num))
    code_smells_num = sqc.get_issues_on_type("CODE_SMELL", project[1]["key"])
    code_smells = resources.span_number_format(int(code_smells_num))

    print "> Retrieving components..."
    duplicated_blocks = resources.span_number_format(
        int(sqc.get_duplicated_blocks(project[1]["key"])))
    duplicity = resources.span_number_format(
        float(sqc.get_duplicated_density(project[1]["key"])))

    print "> Retrieving violated rules..."
    print "        -> BUGS"
    bug_violations = sqc.get_violations(languages, "BUG", project[1]["key"])
    print "        -> VULNERABILITIES"
    vuln_violations = sqc.get_violations(languages,
                                         "VULNERABILITY,SECURITY_HOTSPOT",
                                         project[1]["key"])
    print "        -> CODE SMELL"
    cs_violations = sqc.get_violations(languages, "CODE_SMELL",
                                       project[1]["key"])

    report_date_str = project[1]["lastAnalysisDate"]
    dt = maya.parse(report_date_str).datetime()
    report_date = str(dt.date().day) + "-" + resources.meses[str(
        dt.date().month)] + "-" + str(dt.date().year) + " " + str(dt.time())
    hoy = date.today()
    today = str(hoy.day) + " de " + resources.meses[str(hoy.month) +
                                                    "c"] + " de " + str(
                                                        hoy.year)

    try:
        doc = DocxTemplate("templates/static_detail_report_template.docx")
    except:
        print "> Error. .docx template file not found."
    jinja_env = jinja2.Environment(extensions=['jinja2.ext.loopcontrols'])
    if doc:
        rt = RichText()
        rt.add(
            project[0],
            url_id=doc.build_url_id('http://srv-analiza/sonar/dashboard?id=' +
                                    project[1]["key"]))

        context = {
            'today': today,
            'project_name': project[0],
            'rt': rt,
            'report_date': report_date,
            'ncloc': ncloc,
            'lang_metrics': languages,
            'vulnerabilities': vulnerabilities,
            'bugs': bugs,
            'code_smells': code_smells,
            'duplicated_blocks': duplicated_blocks,
            'duplicity': duplicity,
            'bugs_violations': bug_violations,
            'vuln_violations': vuln_violations,
            'cs_violations': cs_violations,
        }

        doc.render(context, jinja_env)
        doc.save(outputname + ".docx")

    generate_charts(project, languages, sqc, vulnerabilities_num, bugs_num,
                    code_smells_num, outputname)