Пример #1
0
    def save_worklog():
        """Create and save the worklog"""

        def row_to_dict(row):
            d = {
                'Date': str(row.Date.day),
                'Hours': str(row.Hours),
                'Description': row.Comments,
                'Task': ''
            }
            return d

        template = r'../templates/worklog_template.docx'

        document = MailMerge(template)

        # Fill the header
        document.merge(
            Name=name,
            Year=year,
            Month=month,
            Total_hours=str(total_hours),
        )

        # Fill the table
        # print(f"IRAP df hours: {irap_df.Hours}")
        irap_df.Hours = irap_df.Hours.replace(np.nan, 0)
        table_dict = irap_df.replace(np.nan, '').apply(row_to_dict, axis=1)
        document.merge_rows('Date', table_dict)

        file_name = f"{name} {month} {year} IRAP Worklog.docx"
        document.write(file_name)
        st.markdown(get_binary_file_downloader(file_name, file_name), unsafe_allow_html=True)
        document.close()
        print(f"Worklog save successful.")
Пример #2
0
    def merge_test(self):
        template = "..\\data\\Template.docx"

        document = MailMerge(template)
        print(document.get_merge_fields())

        data = {
            'cdm_total': "232",
            'made_by': "최인수",
            'KOMPSAT-2': "123",
            'asdfasd': '12321'
        }

        row = {
            'last_cdm_creation': "test",
            'CDM_NO': "test",
            'CREATION_DATE': "test",
            'PROBABILITY': "test",
            'TCA': "test",
            'EVENTNUM': "test",
            'MISS_DISTANCE': "test",
            'SAT1_NAME': "test",
            'SAT1_NORAD': "test",
        }

        rows = [row, row]

        print(type(data))
        document.merge_rows('CDM_NO', rows)
        document.merge_templates([data], separator='page_break')

        document.write("..\\data\\result.docx")
Пример #3
0
def document():
    content = request.json
    data_entries = []
    
    for i,j,l,m,n in zip(content['data'],content['hours'],content['goals'],content['description'],content['hoursFrequncy']):
        x={}
        x['SupportCategory'] = i['SupportCategoryName']
        x['ItemName'] = i['SupportItemName']
        x['ItemId'] = i['SupportItemNumber']
        
        multiplication = ""
        if (n[-1]=="W"):
            x['H'] = "Hours per Week "+ n.split(',')[0] + "\n" + "Duration " + n.split(',')[1]
            multiplication = n.split(',')[0] + " x " + n.split(',')[1] + "x"
        elif (n[-1]=="M"):
            x['H'] = "Hours per Month "+ n.split(',')[0] + "\n" + "Duration " + n.split(',')[1]
            multiplication = n.split(',')[0] + " x " + n.split(',')[1] + "x"
        else:
            x['H'] = "Hours "+ n
            multiplication = n + " x "
        
        x['Cost'] = multiplication + str(i['Price']) + "\n"+"\n" + str(i['Price']*int(j))

        x['Description'] = str(m)
        goals = ""
        for goal in l:
            goals = goals + goal + "\n" + "\n"
        x['Goals'] = goals
        data_entries.append(x)

    document = MailMerge('WordTemplate.docx')
    document.merge(name=str(content['name']),ndis=str(content['ndis']),sos=str(content['sos']),duration=str(int(content['duration']/7))+" Weeks",start=content['start'],end=content['end'],today=content['today'],policy=content['policy'])
    document.merge_rows('SupportCategory',data_entries)
    document.write('test-output.docx')
    return send_file('test-output.docx', as_attachment=True)
    def makeReport(self, db, template):

        for rule_key in db.keys():
            print(rule_key)
            for did in db[rule_key].keys():
                document = MailMerge(template)
                print(did)
                dr_list = []
                i = 1
                for item in db[rule_key][did]:
                    d = {}
                    d['ListNo'] = str(i)
                    d['FileName'] = item[1]
                    d['FileLine'] = str(item[2])
                    t = catex.catex(d['FileName'])
                    d['FileContent'] = t.catex(item[2], 1, 1)
                    t.close()
                    dr_list.append(d)
                    i = i + 1

                document.merge(DR_Rule_Title=rule_key,
                               DR_Rule_Category=did,
                               DR_Reviewer=self._reviewer,
                               DR_Approver=self._approver,
                               DR_Writer=self._writer)
                document.merge_rows("ListNo", dr_list)
                document.write("result_%s.docx" % (rule_key + did))
                document.close()
Пример #5
0
 def merge_file_tables(self, doc_path, inserted_tables, filename):
     document = MailMerge(doc_path)
     for i in inserted_tables:
         for j in i:
             a = list(j.keys())[1]
         document.merge_rows(a, i)
     document.write(filename)
     return filename
Пример #6
0
def document():
    content = request.json
    data_entries = []
    support_category_map = {}
    for i,j,l,n in zip(content['data'],content['hours'],content['goals'],content['hoursFrequncy']):
        x={}
        SupportCategoryName = i['SupportCategoryName']
        x['SupportCategory'] = SupportCategoryName
        x['ItemName'] = i['SupportItemName']
        x['ItemId'] = i['SupportItemNumber']
        
        multiplication = ""
        if (n[-1]=="W"):
            x['H'] = "Hours per Week: "+ n.split(',')[0] + "\n" + "Duration: " + n.split(',')[1] + " weeks"
            multiplication = n.split(',')[0] + "x" + n.split(',')[1] + "x"
        elif (n[-1]=="M"):
            x['H'] = "Hours per Month: "+ n.split(',')[0] + "\n" + "Duration: " + n.split(',')[1] + " months"
            multiplication = n.split(',')[0] + "x" + n.split(',')[1] + "x"
        else:
            x['H'] = "Hours per plan period: "+ n + " hours"
            multiplication = n + "x"
        
        cost = Money(str(i['Price']*int(j)), 'USD')
        x['Cost'] = multiplication  + Money(str(i['Price']),'USD').format('en_US') + "\n= " + cost.format('en_US')

        if SupportCategoryName in support_category_map:
            support_category_map[SupportCategoryName] += i['Price']*int(j)
        else:
            support_category_map[SupportCategoryName] = i['Price']*int(j)
        
        goals = ""
        for goal in l:
            goals = goals + goal + "\n" + "\n"
        x['Goals'] = goals
        data_entries.append(x)
	
    totalcost = ""
    for key,value in support_category_map.items():
        totalcost = totalcost + key + " = " + Money(str(value),'USD').format('en_US') + "\n"

    document = MailMerge('WordTemplate.docx')
    total_cost = totalcost
    document.merge(totalcost= total_cost.format('en_US'))

    datetimeobject = datetime.strptime(content['start'],'%Y-%m-%d')
    startDate = datetimeobject.strftime('%d/%m/%Y')

    datetimeobject = datetime.strptime(content['end'],'%Y-%m-%d')
    endDate = datetimeobject.strftime('%d/%m/%Y')


    datetimeobject = datetime.strptime(content['today'],'%Y-%m-%d')
    today = datetimeobject.strftime('%d/%m/%Y')

    document.merge(name=str(content['name']),ndis=str(content['ndis']),sos=str(content['sos']),duration=str(int(content['duration']/7))+" weeks",start=startDate,end=endDate,today=today,policy=content['policy'])
    document.merge_rows('SupportCategory',data_entries)
    document.write('test-output.docx')
    return send_file('test-output.docx', as_attachment=True)
Пример #7
0
def generar_hoja_valoracion_social(request, pk):
    persona = Persona.objects.get(pk=pk, active=True)

    template = os.path.join(os.path.abspath('source_files'), 'vl.docx')
    document = MailMerge(template)

    hijos = []

    for h in persona.hijo.all():
        hijo_dict = {}
        hijo_dict['parentesco'] = f'{h.parentesco}'
        hijo_dict['nombre_apellido_hijo'] = f'{h.nombre_apellido}'
        hijo_dict['dni_hijo'] = f'{h.dni}'
        hijo_dict[
            'fecha_nacimiento_hijo'] = f"{'{:%d-%m-%Y}'.format(h.fecha_nacimiento)}"
        hijos.append(hijo_dict)
    document.merge(
        numar_adra=f'{persona.numero_adra}',
        nombre_apellido=f'{persona.nombre_apellido}',
        dni=f'{persona.dni}',
        fecha_nacimiento=f"{'{:%d-%m-%Y}'.format(persona.fecha_nacimiento)}",
        nacionalidad=f'{persona.nacionalidad}',
        domicilio=f'{persona.domicilio}',
        ciudad=f'{persona.ciudad}',
        numar_telefon=f'{persona.telefono}',
        # fecha_hoy=f"{'{:%d-%m-%Y}'.format(persona.created_at) }",
        fecha_hoy="",
    )
    if persona.empadronamiento:
        document.merge(a="x")
    if persona.libro_familia:
        document.merge(b="x")
    if persona.fotocopia_dni:
        document.merge(c="x")
    if persona.prestaciones:
        document.merge(d="x")
    if persona.nomnia:
        document.merge(e="x")
    if persona.cert_negativo:
        document.merge(f="x")
    if persona.aquiler_hipoteca:
        document.merge(g="x")
    if persona.recibos:
        document.merge(h="x")
    document.merge_rows('parentesco', hijos)

    # document.write(f'./valoracion/{p.numero_adra}.docx')

    response = HttpResponse(
        content_type=
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )
    response[
        'Content-Disposition'] = f'attachment; filename={persona.numero_adra}.docx'
    document.write(response)

    return response
Пример #8
0
 def write_final_options(self, name):
     template = "test-print.docx"
     document = MailMerge(template)
     document.merge_rows('item', docx_dict)
     document.merge(**merge2)
     if name.endswith('.docx'):
         document.write(name)
     else:
         document.write(name + '.docx')
     document.close()
Пример #9
0
 def merge_file_fields_tables(self, doc_path, inserted_fields,
                              inserted_tables2, filename):
     document = MailMerge(doc_path)
     for i in inserted_tables2:
         for j in i:
             a = list(j.keys())[0]
         document.merge_rows(a, i)
     document.merge_pages([inserted_fields])
     document.write(filename)
     return filename
class MergeTableRowsMultipartTest(EtreeMixin, unittest.TestCase):
    def setUp(self):
        self.document = MailMerge(path.join(path.dirname(__file__), 'test_merge_table_multipart.docx'))
        self.expected_xml = '<w:document xmlns:ns1="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p w:rsidP="00DA4DE0" w:rsidR="00231DA5" w:rsidRDefault="00DA4DE0"><w:pPr><w:pStyle w:val="Ttulo" /></w:pPr><w:r><w:t>Grades</w:t></w:r></w:p><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>Bouke Haarsma</w:t></w:r><w:r w:rsidR="002C29C5"><w:t xml:space="preserve"> </w:t></w:r><w:r w:rsidR="00DA4DE0"><w:t>received the grades</w:t></w:r><w:r w:rsidR="002C29C5"><w:t xml:space="preserve"> for </w:t></w:r><w:r><w:t /></w:r><w:r w:rsidR="00DA4DE0"><w:t xml:space="preserve"> in the table below.</w:t></w:r></w:p><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0" /><w:tbl><w:tblPr><w:tblStyle w:val="Sombreadoclaro-nfasis1" /><w:tblW w:type="auto" w:w="0" /><w:tblLook w:val="04E0" /></w:tblPr><w:tblGrid><w:gridCol w:w="1777" /><w:gridCol w:w="4894" /><w:gridCol w:w="1845" /></w:tblGrid><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="100000000000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:r><w:t>Class Code</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:pPr><w:cnfStyle w:val="100000000000" /></w:pPr><w:r><w:t>Class Name</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:pPr><w:cnfStyle w:val="100000000000" /></w:pPr><w:r><w:t>Grade</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>ECON101</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>Economics 101</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>ECONADV</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>Economics Advanced</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>B</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>OPRES</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>Operations Research</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00C829DD" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="010000000000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="00C829DD"><w:r><w:t>THESIS</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:val="010000000000" /></w:pPr><w:r><w:t>Final thesis</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="010000000000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0" w:rsidRPr="00DA4DE0"><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00DA4DE0" w:rsidRPr="00DA4DE0" w:rsidSect="003B4151"><w:headerReference ns1:id="rId7" w:type="default" /><w:pgSz w:h="16840" w:w="11900" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1800" w:right="1800" w:top="1672" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body></w:document>'
        self.expected_tree = etree.fromstring(self.expected_xml) 

    def test_merge_rows_on_multipart_file(self):
        self.assertEqual(self.document.get_merge_fields(),
                         {'student_name', 'study_name', 'class_name', 'class_code', 'class_grade', 'thesis_grade'})

        self.document.merge(
            student_name='Bouke Haarsma',
            study='Industrial Engineering and Management',
            thesis_grade='A',
        )

        self.document.merge_rows('class_code', [
            {'class_code': 'ECON101', 'class_name': 'Economics 101', 'class_grade': 'A'},
            {'class_code': 'ECONADV', 'class_name': 'Economics Advanced', 'class_grade': 'B'},
            {'class_code': 'OPRES', 'class_name': 'Operations Research', 'class_grade': 'A'},
        ])

        with tempfile.TemporaryFile() as outfile:
            self.document.write(outfile)

        for part in self.document.parts.values():
            # only check the document part 
            if (part.getroot().tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}document'):
                self.assert_equal_tree(self.expected_tree, part.getroot())

    def test_merge_unified_on_multipart_file(self):
        self.document.merge(
            student_name='Bouke Haarsma',
            study='Industrial Engineering and Management',
            thesis_grade='A',
            class_code=[
                {'class_code': 'ECON101', 'class_name': 'Economics 101', 'class_grade': 'A'},
                {'class_code': 'ECONADV', 'class_name': 'Economics Advanced', 'class_grade': 'B'},
                {'class_code': 'OPRES', 'class_name': 'Operations Research', 'class_grade': 'A'},
            ]
        )

        with tempfile.TemporaryFile() as outfile:
            self.document.write(outfile)

        for part in self.document.parts.values():
            # only check the document part 
            if (part.getroot().tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}document'):
                self.assert_equal_tree(self.expected_tree, part.getroot())

    def tearDown(self):
        self.document.close()
Пример #11
0
def populate_doc(frameX, frameY, patent_listX, patent_listY):
    template = "TEMPLATE 5.docx"
    document = MailMerge(template)
    XListofdict = []
    YListofdict = []
    XList2ofdict = []

    for x in range(len(patent_listX)):
        Xdict = {}
        Xdict["X_PAT_NUMBER"] = frameX.iloc[x, 0]
        Xdict["X_PAT_TITLE"] = frameX.iloc[x, 1]
        Xdict["X_PAT_ASSIGNEE"] = frameX.iloc[x, 6]
        Xdict["X_PAT_PUBDATE"] = frameX.iloc[x, 5]
        Xdict["X_PAT_APPDATE"] = frameX.iloc[x, 3]
        Xdict["X_PAT_PRIORDATE"] = frameX.iloc[x, 4]
        Xdict["X_PAT_INVENTORS"] = frameX.iloc[x, 7]
        Xdict["X_PAT_FAMILY"] = frameX.iloc[x, 8]
        XListofdict.append(Xdict)

    if len(patent_listY) > 1:
        print patent_listY
        for x in range(len(patent_listY)):
            Ydict = {}
            Ydict["Y_PAT_NUMBER"] = frameY.iloc[x, 0]
            Ydict["Y_PAT_TITLE"] = frameY.iloc[x, 1]
            Ydict["Y_PAT_ASSIGNEE"] = frameY.iloc[x, 6]
            Ydict["Y_PAT_PUBDATE"] = frameY.iloc[x, 5]
            Ydict["Y_PAT_APPDATE"] = frameY.iloc[x, 3]
            Ydict["Y_PAT_PRIORDATE"] = frameY.iloc[x, 4]
            Ydict["Y_PAT_INVENTORS"] = frameY.iloc[x, 7]
            Ydict["Y_PAT_FAMILY"] = frameY.iloc[x, 8]
            YListofdict.append(Ydict)

    for x in range(len(patent_listX)):
        Xdict1 = {}
        Xdict1["X_PAT_{}_NUMBER".format(x + 1)] = frameX.iloc[x, 0]
        Xdict1["X_PAT_{}_TITLE".format(x + 1)] = frameX.iloc[x, 1]
        Xdict1["X_PAT_{}_ASSIGNEE".format(x + 1)] = frameX.iloc[x, 6]
        Xdict1["X_PAT_{}_PUBDATE".format(x + 1)] = frameX.iloc[x, 5]
        Xdict1["X_PAT_{}_APPDATE".format(x + 1)] = frameX.iloc[x, 3]
        Xdict1["X_PAT_{}_PRIORDATE".format(x + 1)] = frameX.iloc[x, 4]
        Xdict1["X_PAT_{}_INVENTORS".format(x + 1)] = frameX.iloc[x, 7]
        Xdict1["X_PAT_{}_FAMILY".format(x + 1)] = frameX.iloc[x, 8]
        XList2ofdict.append(Xdict1)

    #print YListofdict
    document.merge_rows('X_PAT_NUMBER', XListofdict)
    document.merge_rows('Y_PAT_NUMBER', YListofdict)
    document.merge_pages(XList2ofdict)
    #document.merge(**Ydict)
    document.write('NEW REPORT1.docx')
class MergeTableRowsMultipartTest(EtreeMixin, unittest.TestCase):
    def setUp(self):
        self.document = MailMerge(path.join(path.dirname(__file__), 'test_merge_table_multipart.docx'))
        self.expected_xml = '<w:document xmlns:ns1="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p w:rsidP="00DA4DE0" w:rsidR="00231DA5" w:rsidRDefault="00DA4DE0"><w:pPr><w:pStyle w:val="Ttulo" /></w:pPr><w:r><w:t>Grades</w:t></w:r></w:p><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>Bouke Haarsma</w:t></w:r><w:r w:rsidR="002C29C5"><w:t xml:space="preserve"> </w:t></w:r><w:r w:rsidR="00DA4DE0"><w:t>received the grades</w:t></w:r><w:r w:rsidR="002C29C5"><w:t xml:space="preserve"> for </w:t></w:r><w:r><w:t /></w:r><w:r w:rsidR="00DA4DE0"><w:t xml:space="preserve"> in the table below.</w:t></w:r></w:p><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0" /><w:tbl><w:tblPr><w:tblStyle w:val="Sombreadoclaro-nfasis1" /><w:tblW w:type="auto" w:w="0" /><w:tblLook w:val="04E0" /></w:tblPr><w:tblGrid><w:gridCol w:w="1777" /><w:gridCol w:w="4894" /><w:gridCol w:w="1845" /></w:tblGrid><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="100000000000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:r><w:t>Class Code</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:pPr><w:cnfStyle w:val="100000000000" /></w:pPr><w:r><w:t>Class Name</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:pPr><w:cnfStyle w:val="100000000000" /></w:pPr><w:r><w:t>Grade</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>ECON101</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>Economics 101</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>ECONADV</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>Economics Advanced</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>B</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:r><w:t>OPRES</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>Operations Research</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="000000100000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr><w:tr w:rsidR="00C829DD" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:val="010000000000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="00C829DD"><w:r><w:t>THESIS</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:val="010000000000" /></w:pPr><w:r><w:t>Final thesis</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="0037127B"><w:pPr><w:cnfStyle w:val="010000000000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0" w:rsidRPr="00DA4DE0"><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00DA4DE0" w:rsidRPr="00DA4DE0" w:rsidSect="003B4151"><w:headerReference ns1:id="rId7" w:type="default" /><w:pgSz w:h="16840" w:w="11900" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1800" w:right="1800" w:top="1672" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body></w:document>'
        self.expected_tree = ElementTree.fromstring(self.expected_xml) 

    def test_merge_rows_on_multipart_file(self):
        self.assertEqual(self.document.get_merge_fields(),
                         {'student_name', 'study_name', 'class_name', 'class_code', 'class_grade', 'thesis_grade'})

        self.document.merge(
            student_name='Bouke Haarsma',
            study='Industrial Engineering and Management',
            thesis_grade='A',
        )

        self.document.merge_rows('class_code', [
            {'class_code': 'ECON101', 'class_name': 'Economics 101', 'class_grade': 'A'},
            {'class_code': 'ECONADV', 'class_name': 'Economics Advanced', 'class_grade': 'B'},
            {'class_code': 'OPRES', 'class_name': 'Operations Research', 'class_grade': 'A'},
        ])

        with tempfile.TemporaryFile() as outfile:
            self.document.write(outfile)

        for part in self.document.parts.values():
            # only check the document part 
            if (part.getroot().tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}document'):
                self.assert_equal_tree(self.expected_tree, part.getroot())

    def test_merge_unified_on_multipart_file(self):
        self.document.merge(
            student_name='Bouke Haarsma',
            study='Industrial Engineering and Management',
            thesis_grade='A',
            class_code=[
                {'class_code': 'ECON101', 'class_name': 'Economics 101', 'class_grade': 'A'},
                {'class_code': 'ECONADV', 'class_name': 'Economics Advanced', 'class_grade': 'B'},
                {'class_code': 'OPRES', 'class_name': 'Operations Research', 'class_grade': 'A'},
            ]
        )

        with tempfile.TemporaryFile() as outfile:
            self.document.write(outfile)

        for part in self.document.parts.values():
            # only check the document part 
            if (part.getroot().tag == '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}document'):
                self.assert_equal_tree(self.expected_tree, part.getroot())
Пример #13
0
class MergeReport:
    document = None

    def merge_init(self):
        template = iface.LOC_REPORT_TEMPLATE
        self.document = MailMerge(template)

    def merge_table_data(self, anchor, data):
        self.document.merge_rows(anchor, data)

    def merge_plain_data(self, data):
        self.document.merge_templates([data], separator='page_break')

    def merge_create_report(self, fname):
        self.document.write(iface.LOC_DAILY_REPORT.format(fname))

    def merge_test(self):
        template = "..\\data\\Template.docx"

        document = MailMerge(template)
        print(document.get_merge_fields())

        data = {
            'cdm_total': "232",
            'made_by': "최인수",
            'KOMPSAT-2': "123",
            'asdfasd': '12321'
        }

        row = {
            'last_cdm_creation': "test",
            'CDM_NO': "test",
            'CREATION_DATE': "test",
            'PROBABILITY': "test",
            'TCA': "test",
            'EVENTNUM': "test",
            'MISS_DISTANCE': "test",
            'SAT1_NAME': "test",
            'SAT1_NORAD': "test",
        }

        rows = [row, row]

        print(type(data))
        document.merge_rows('CDM_NO', rows)
        document.merge_templates([data], separator='page_break')

        document.write("..\\data\\result.docx")
Пример #14
0
def patient_report(data):
    patient_data = data.get('patient')
    ekgs_data = data.get('ekgs')

    for item in ekgs_data:
        for key, value in item.items():
            item[key] = str(value)

    document = MailMerge(patient_template)
    document.merge_pages([patient_data])
    document.merge_rows('ekg_id', ekgs_data)
    filename = f"Отчет_по_пациенту_{patient_data.get('patient_id')}.docx"
    new_file_path = f"{path}/templates/{filename}"
    document.write(new_file_path)

    return filename
class MergeTableRowsTest(EtreeMixin, unittest.TestCase):
    def setUp(self):
        self.document = MailMerge(path.join(path.dirname(__file__), 'test_merge_table_rows.docx'))
        self.expected_tree = ElementTree.fromstring('<w:document xmlns:ns1="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p ns1:paraId="28ACC80D" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00231DA5" w:rsidRDefault="00DA4DE0"><w:pPr><w:pStyle w:val="Title" /></w:pPr><w:proofErr w:type="spellStart" /><w:r><w:t>Grades</w:t></w:r><w:proofErr w:type="spellEnd" /></w:p><w:p ns1:paraId="07836F52" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:r><w:t>Bouke Haarsma</w:t></w:r><w:r w:rsidR="002C29C5"><w:t xml:space="preserve"> </w:t></w:r><w:proofErr w:type="spellStart" /><w:r w:rsidR="00DA4DE0"><w:t>received</w:t></w:r><w:proofErr w:type="spellEnd" /><w:r w:rsidR="00DA4DE0"><w:t xml:space="preserve"> the </w:t></w:r><w:proofErr w:type="spellStart" /><w:r w:rsidR="00DA4DE0"><w:t>grades</w:t></w:r><w:proofErr w:type="spellEnd" /><w:r w:rsidR="002C29C5"><w:t xml:space="preserve"> </w:t></w:r><w:proofErr w:type="spellStart" /><w:r w:rsidR="002C29C5"><w:t>for</w:t></w:r><w:proofErr w:type="spellEnd" /><w:r w:rsidR="002C29C5"><w:t xml:space="preserve"> </w:t></w:r><w:r><w:t /></w:r><w:r w:rsidR="00DA4DE0"><w:t xml:space="preserve"> in the </w:t></w:r><w:proofErr w:type="spellStart" /><w:r w:rsidR="00DA4DE0"><w:t>table</w:t></w:r><w:proofErr w:type="spellEnd" /><w:r w:rsidR="00DA4DE0"><w:t xml:space="preserve"> below.</w:t></w:r></w:p><w:p ns1:paraId="58525309" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0" /><w:tbl><w:tblPr><w:tblStyle w:val="LightShading-Accent1" /><w:tblW w:type="auto" w:w="0" /><w:tblLook w:firstColumn="1" w:firstRow="1" w:lastColumn="0" w:lastRow="1" w:noHBand="0" w:noVBand="1" w:val="04E0" /></w:tblPr><w:tblGrid><w:gridCol w:w="1777" /><w:gridCol w:w="4894" /><w:gridCol w:w="1845" /></w:tblGrid><w:tr ns1:paraId="599252DD" ns1:textId="77777777" w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="1" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="100000000000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="1" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p ns1:paraId="69486D96" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:r><w:t>Class Code</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p ns1:paraId="1AA11439" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="1" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="100000000000" /></w:pPr><w:r><w:t>Class Name</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p ns1:paraId="3091846F" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="1" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="100000000000" /></w:pPr><w:r><w:t>Grade</w:t></w:r></w:p></w:tc></w:tr><w:tr ns1:paraId="1699D5B6" ns1:textId="77777777" w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="1" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p ns1:paraId="5D81DF7F" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:r><w:t>ECON101</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p ns1:paraId="5A67E49A" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:pPr><w:r><w:t>Economics 101</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p ns1:paraId="5EB9BD23" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr><w:tr ns1:paraId="1699D5B6" ns1:textId="77777777" w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="1" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p ns1:paraId="5D81DF7F" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:r><w:t>ECONADV</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p ns1:paraId="5A67E49A" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:pPr><w:r><w:t>Economics Advanced</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p ns1:paraId="5EB9BD23" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:pPr><w:r><w:t>B</w:t></w:r></w:p></w:tc></w:tr><w:tr ns1:paraId="1699D5B6" ns1:textId="77777777" w:rsidR="00DA4DE0" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="1" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p ns1:paraId="5D81DF7F" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:r><w:t>OPRES</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p ns1:paraId="5A67E49A" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:pPr><w:r><w:t>Operations Research</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p ns1:paraId="5EB9BD23" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="1" w:oddVBand="0" w:val="000000100000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr><w:tr ns1:paraId="0B5730FD" ns1:textId="77777777" w:rsidR="00C829DD" w:rsidTr="00C829DD"><w:trPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="1" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="010000000000" /></w:trPr><w:tc><w:tcPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="1" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="0" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="001000000000" /><w:tcW w:type="dxa" w:w="1809" /></w:tcPr><w:p ns1:paraId="6A211A5A" ns1:textId="4E90EB38" w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="00C829DD"><w:r><w:t>THESIS</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="5529" /></w:tcPr><w:p ns1:paraId="12FCE443" ns1:textId="289CA6C6" w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="1" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="010000000000" /></w:pPr><w:proofErr w:type="spellStart" /><w:r><w:t>Final</w:t></w:r><w:proofErr w:type="spellEnd" /><w:r><w:t xml:space="preserve"> thesis</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:type="dxa" w:w="1178" /></w:tcPr><w:p ns1:paraId="0ACD9198" ns1:textId="413A3A4D" w:rsidP="00DA4DE0" w:rsidR="00C829DD" w:rsidRDefault="00C829DD"><w:pPr><w:cnfStyle w:evenHBand="0" w:evenVBand="0" w:firstColumn="0" w:firstRow="0" w:firstRowFirstColumn="0" w:firstRowLastColumn="0" w:lastColumn="0" w:lastRow="1" w:lastRowFirstColumn="0" w:lastRowLastColumn="0" w:oddHBand="0" w:oddVBand="0" w:val="010000000000" /></w:pPr><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr></w:tbl><w:p ns1:paraId="26A87379" ns1:textId="77777777" w:rsidP="00DA4DE0" w:rsidR="00DA4DE0" w:rsidRDefault="00DA4DE0" w:rsidRPr="00DA4DE0"><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00DA4DE0" w:rsidRPr="00DA4DE0" w:rsidSect="002C0659"><w:pgSz w:h="16840" w:w="11900" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1800" w:right="1800" w:top="1440" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body></w:document>')  # noqa

    def test_merge_rows(self):
        self.assertEqual(self.document.get_merge_fields(),
                         {'student_name', 'study_name', 'class_name', 'class_code', 'class_grade', 'thesis_grade'})

        self.document.merge(
            student_name='Bouke Haarsma',
            study='Industrial Engineering and Management',
            thesis_grade='A',
        )

        self.document.merge_rows('class_code', [
            {'class_code': 'ECON101', 'class_name': 'Economics 101', 'class_grade': 'A'},
            {'class_code': 'ECONADV', 'class_name': 'Economics Advanced', 'class_grade': 'B'},
            {'class_code': 'OPRES', 'class_name': 'Operations Research', 'class_grade': 'A'},
        ])

        with tempfile.TemporaryFile() as outfile:
            self.document.write(outfile)

        self.assert_equal_tree(self.expected_tree,
                               list(self.document.parts.values())[0].getroot())

    def test_merge_unified(self):
        self.document.merge(
            student_name='Bouke Haarsma',
            study='Industrial Engineering and Management',
            thesis_grade='A',
            class_code=[
                {'class_code': 'ECON101', 'class_name': 'Economics 101', 'class_grade': 'A'},
                {'class_code': 'ECONADV', 'class_name': 'Economics Advanced', 'class_grade': 'B'},
                {'class_code': 'OPRES', 'class_name': 'Operations Research', 'class_grade': 'A'},
            ]
        )

        with tempfile.TemporaryFile() as outfile:
            self.document.write(outfile)

        self.assert_equal_tree(self.expected_tree,
                               list(self.document.parts.values())[0].getroot())
Пример #16
0
def download():
    """Generates a file and returns to the user."""

    data = set(cache.get('current_data'))
    filename = cache.get('filename')

    if filename is None:
        return render_template('entry.html', headings=headings, data=data)
    else:
        filename = str(filename)

    uploads = os.path.join(APP_ROUTE, "uploads/")

    document = MailMerge(uploads + filename)
    data = set(cache.get('current_data'))

    initials = request.form.get('full_name')
    county_name = request.form.get('county_name')
    count_cars = request.form.get('count_cars')

    document.merge(fio=initials, county_name=county_name, supplier=count_cars)

    # list of data that will be substituted into the word template.
    data_word_list = []

    # Populating the list with data.
    for row in data:
        data_word_list.append(
            {
                'model_name': str(row[0]),
                'date_of_purchase': str(row[1]),
                'count_of_cars': str(row[2]),
                'cost': str(row[3]),
            }, )

    document.merge_rows('model_name', data_word_list)

    ready_template_name = uploads + FILE_READY_TEMPLATE_NAME

    document.write(ready_template_name)

    return send_file(ready_template_name)
 def CreateDoc(self, issues):
     document = MailMerge(self.DocxSource)
     print(document.get_merge_fields())
     #Заголовок
     document.merge(ProjectName=self.Project)
     document.merge(VersionName=self.Version)        
     # Список ошибок
     dict = self.getIssuesDict(issues)
     document.merge_rows('IssueSubject', dict)
     # Номер ревизии    
     document.merge(Revision=str(self.Revision))
     # Ошибок найдено (кол-во / вес)        
     document.merge(IssuesTotal=str(len(issues)))
     document.merge(WeightsTotal=str(sum(issue.Weight for issue in issues)))
     # Ошибок не исправлено (кол-во / вес)
     document.merge(IssuesOpen=str(len([issue for issue in issues if not issue.Result])))
     document.merge(WeightsOpen=str(sum(issue.Weight for issue in issues if not issue.Result)))
     # Контрольная сумма (MD5)
     document.merge(InstallerChecksum=str(self.InstallerChecksum))
     # Сохранение дока
     document.write(self.DocxDestination)
Пример #18
0
def doc_report(data):
    patient_data = data.get('patient')
    ekgs_data = data.get('ekgs')

    svg = data.get('svg')

    svg = '<svg' + svg.split('<svg')[-1]
    svg = svg.split('<path')
    svg = svg[0] + ''.join(['<path ' + 'style="fill:none;"' + p for p in svg[1:]])

    with open(f"{path}/templates/img.svg", 'w') as f:
        f.write(svg)
    drawing = svg2rlg(f"{path}/templates/img.svg")
    sx = sy = 3
    drawing.width, drawing.height = drawing.minWidth() * sx, drawing.height * sy
    drawing.scale(sx, sy)
    image_path = f"{path}/templates/img.jpg"
    renderPM.drawToFile(drawing, image_path, fmt="JPG")

    for item in ekgs_data:
        for key, value in item.items():
            item[key] = str(value)

    document = MailMerge(doc_template)
    document.merge_pages([patient_data])
    document.merge_rows('ekg_id', ekgs_data)
    filename = f"Отчет_по_пациенту_{patient_data.get('patient_id')}_(для_врача).docx"
    new_file_path = f"{path}/templates/{filename}"
    document.write(new_file_path)

    tpl = DocxTemplate(new_file_path)
    context = {
        'Image': InlineImage(tpl, image_path, width=Mm(190))
    }
    jinja_env = jinja2.Environment(autoescape=True)
    tpl.render(context, jinja_env)
    tpl.save(new_file_path)

    return filename
Пример #19
0
 def izvjestaj(self, template):
     ddatum = date.today()
     ddatum = ddatum.strftime("%d/%b/%y")
     document = MailMerge(template)
     df = self.grupisanjeDF()
     df['masa'] = df.apply(lambda row: row.Razlika * 12.5
                           if row.profil == '3.5x3.5' else row.Razlika * 9,
                           axis=1)
     df['tone'] = df['masa'].apply(lambda x: x * 1.6)
     df = df.round({
         'Duz_current': 3,
         'Duz_previous': 3,
         'Razlika': 3,
         'masa': 3,
         'tone': 3
     }).applymap(str)
     dct_table = df.to_dict('record')
     document.merge(datum=ddatum)
     document.merge_rows('Duz_current', dct_table)
     document.merge_rows('tone', dct_table)
     document.write('test.docx')
     history = pd.DataFrame(list(zip(df['radiliste'], df['Duz_current'])),
                            columns=['radiliste', ddatum])
     return history
Пример #20
0
document = MailMerge(template)
print(document.get_merge_fields())

today = date.date.today()
nextWeek = today + date.timedelta(days=7)

document.merge(invoiceNumber="AB001",
               invoiceDate='{:%d-%b-%Y}'.format(date.date.today()),
               clientCompany="The Anderson Lid Company",
               dueDate=str(nextWeek))

invoice_list = [{
    'description': 'SPI TRAY: 3D Printing Service (Large Format)',
    'quantity': '40.00',
    'unitPrice': '20.00',
    'amount': '800.00'
}, {
    'description': 'SPI TRAY: 3D Printing Filament (PETG)',
    'quantity': '0.796',
    'unitPrice': '1,250.00',
    'amount': '995.00'
}, {
    'description': 'SPI TRAY: Printer Setup',
    'quantity': '1.00',
    'unitPrice': '50.00',
    'amount': '50.00'
}]

document.merge_rows('description', invoice_list)
document.write('test-output.docx')
    '할인': '2%',
    '수신자': '김유신'
}

document_2 = MailMerge(template_1)
document_2.merge_pages([고객_1, 고객_2, 고객_3])
document_2.write('example2.docx')

# Final Example includes a table with the sales history

구매이력 = [{
    '물품': '사과',
    '가격': '1,000원',
    '수량': '25개',
    '금액': '25,000원'
}, {
    '물품': '배',
    '가격': '2,000원',
    '수량': '10개',
    '금액': '20,000원'
}, {
    '물품': '딸기',
    '가격': '5,000원',
    '수량': '40개',
    '금액': '200,000원'
}]

document_3 = MailMerge(template_2)
document_3.merge(**고객_3)
document_3.merge_rows('물품', 구매이력)
document_3.write('example3.docx')
        for row in range(extra_labels):
            row_list.append({
                'NumberOfBottles': '__',
                'Container': '',
                'ProjectName': project_name,
                'AnalysisSuite': '',
                'SampleID': '',
                'BottleNumber': '__',
                'Preservative': ''
            })

        #print row_list

        ## Do the Mail Merge
        print 'Merging fields'
        document.merge_rows('NumberOfBottles', row_list)

        ## Write the file
        print 'Writing labels'
        document.write(maindir + Coc_Excel_File + '-labels_output.docx')

        ## Number of Labels
        number_of_labels = len(merge_fields) + extra_labels
        print
        print
        print 'Wrote ' + str(number_of_labels) + ' labels: ' + str(
            len(merge_fields)) + ' project labels, and ' + str(
                extra_labels) + ' extra labels'
        print
        print 'Good luck sampling!!'
        print 'press any key to exit....'
Пример #23
0

def get_work_events(excel_sheet):
    work_events = []
    total_billed = 0
    for i in range(11, excel_sheet.nrows):
        row_values = excel_sheet.row_values(i)
        year, month, day = xlrd.xldate_as_tuple(row_values[0], 0)[:3]
        title = row_values[1]
        duration = row_values[2]
        total_billed += duration * 150
        description = row_values[3]
        work_event = {
            'Date': '{}/{}/{}'.format(month, day, year),
            'WorkTitle': title,
            'Duration': str(duration),
            'WorkDescription': description,
            'AmountBilled': '${}.00'.format(str(int(duration) * 150))
        }
        work_events.append(work_event)
    return work_events, total_billed


invoice_info = get_invoice_info(excel_sheet)
work_events, total_billed = get_work_events(excel_sheet)
invoice_info['TotalBilled'] = '${}.00'.format(str(int(total_billed)))

document.merge(**invoice_info)
document.merge_rows('WorkTitle', work_events)
document.write('reports/Invoice - {}.docx'.format(date.today()))
Пример #24
0
from __future__ import print_function
from mailmerge import MailMerge
from datetime import date
import json

template = "templates/master.docx"
database = "databases/data.json"

file = MailMerge(template)

with open(database) as data_file:
    data = json.load(data_file)

personalInfo = data["personal_info"]

client_name = personalInfo["client_name"]
vehiclesList = data["vehicles"]

createdDoc = "docx/" + client_name.replace(" ", "") + ".docx"

file.merge(**personalInfo)

file.merge_rows('vehicle_no', vehiclesList)
file.merge_rows('summ_vehicle_no', vehiclesList)

file.write(createdDoc)
Пример #25
0
            #Formatting subtotals
            raw_subtotal = sheet.cell(row=cell_row, column=7).value
            #appending raw number for the total calculation
            raw_subtotal_list.append(raw_subtotal)

            #convert the number into a string and format (example 1,278.25)
            clean_subtotal = "{:,.2f}".format(raw_subtotal)

            #Appending product as a dict into a list, which will
            # be merged as a table
            product_dict = {
                'Date': clean_date_time,
                'Item': str(sheet.cell(row=cell_row, column=4).value),
                'Quantity': str(sheet.cell(row=cell_row, column=5).value),
                'Cost': str(sheet.cell(row=cell_row, column=6).value),
                'Subtotal': clean_subtotal
            }

            #Appending dicts to merge as a table
            sales_history_list.append(product_dict)

    # summing raw numbers into a total
    total = sum(raw_subtotal_list)

    # Merging the name and formatting totals
    word_doc.merge(Name=rep, Total="{:,.2f}".format(total))
    word_doc.merge_rows('Date', sales_history_list)  #merge which creates table
    word_doc.write(
        f'Sales Order for {rep}.docx')  #Creates Word doc and names it
Пример #26
0
def personalInformation(name, year, dob, email, enrollment, department, gender,
                        specialization, mobile, graduationYear, graduationCgpa,
                        twelfthOrDiploma, twelfthYear, twelfthBoard,
                        twelfthSchool, twelfthCgpa, tenthYear, tenthBoard,
                        tenthSchool, tenthCgpa, scholastic_achievements,
                        projects, work_exp, position_of_responsibility,
                        extra_curricular, operating_systems,
                        programming_skills, web_designing, software_skills,
                        core_subject, depth_subject):
    template = "./resume_template.docx"
    document = MailMerge(template)
    document.merge(Name=name.title())
    document.merge(Year=year + " Year")
    document.merge(DOB=dob)
    document.merge(gmail=email)
    document.merge(enrollment=enrollment)
    document.merge(Department=department)
    document.merge(gender=gender)
    document.merge(specialization=specialization)
    document.merge(Mobile=mobile)

    document.merge(graduation_year=graduationYear)
    document.merge(graduation_cgpa=graduationCgpa)
    document.merge(twelfth_Diploma=twelfthOrDiploma)
    document.merge(twelfth_school=twelfthSchool)
    document.merge(twelfth_board=twelfthBoard)
    document.merge(twelfth_pass=twelfthYear)
    document.merge(twelfth_cgpa=twelfthCgpa)
    document.merge(tenth_school=tenthSchool)
    document.merge(tenth_board=tenthBoard)
    document.merge(tenth_pass=tenthYear)
    document.merge(tenth_cgpa=tenthCgpa)

    document.merge(operating_systems=", ".join(operating_systems))
    document.merge(programming_skills=", ".join(programming_skills))
    document.merge(web_designing=", ".join(web_designing))
    document.merge(software_skills=", ".join(software_skills))

    document.merge(core_subject="\n•   ".join(core_subject))
    document.merge(depth_subject="\n•   ".join(depth_subject))

    cust_2 = {
        'status': 'Silver',
        'city': 'Columbus',
        'phone_number': '800-555-5551',
        'Business': 'Fancy Pants',
        'zip': '55551',
        'purchases': '$250,000',
        'shipping_limit': '$2000',
        'state': 'OH',
        'address': '1234 Elm St',
        'discount': '2%',
        'recipient': 'Mrs. Smith'
    }
    document.merge(**cust_2)

    document.merge_rows('sa_description', scholastic_achievements)

    document.merge_rows('pro_description', projects)

    document.merge_rows('work_place', work_exp)

    document.merge_rows('pos_position', position_of_responsibility)

    document.merge_rows('ec_event', extra_curricular)

    filename = enrollment + "_" + name + ".docx"

    document.write(filename)

    emailp.sendMail(email, filename)
Пример #27
0
		SELECT barang.`NAMABARANG`, barang.`KODEBARANG`, barang.`JUMLAHBARANG`, barang.`HARGABARANG`,barang.`TANGGALMASUK`, kondisi.`NAMAKONDISI`, merk.`NAMAMERK`, sumber.`NAMASUMBER`, lokasi.`NAMALOKASI` 
		FROM barang INNER JOIN kondisi ON kondisi.`IDKONDISI` = barang.`IDKONDISI`
		INNER JOIN merk ON merk.`IDMERK` = barang.`IDMERK` 
		INNER JOIN sumber ON sumber.`IDSUMBER` = barang.`IDSUMBER` 
		INNER JOIN lokasi ON lokasi.`IDLOKASI` = barang.`IDLOKASI` WHERE barang.IDBARANG =''' + str(nama_barang) +  " GROUP BY barang.`IDBARANG`"
	#print sql
	cur.execute(sql)

	data = []
	document = MailMerge(path+'LabelSDMI1.docx')
	for row in cur.fetchall():
		i = row[2]
		for x in range(i):
			temp = {}
			temp['tahun'] = str(row[4].year)
			temp['asal_dana']		= row[7]
			temp['nama_barang']		= row[0]
			temp['no_barang']		= row[1]
			temp['lokasi'] = row[8]
			temp['no'] = str(x+1)
			data.append(temp)

	document.merge_rows('no_barang', data)
	document.write(path+nama_file + '.docx')

cur.close()
db.close()

end = time.time()
elapsed = end - start
print str(elapsed) + " detik"
Пример #28
0
def create_sender_table(file_name, sender, receiver, r_date):
    template_file = "./demo.docx"
    file_path = file_name
    target_name = file_path.split("/")[-1].split(".")[0]
    target_name = target_name + "_거래내역서.docx"
    target_path = file_path.split("/")[:-1]
    target_path = "/".join(target_path)
    target_path = target_path + "/" + target_name
    print("File_path:", file_path)
    print("Target_path:", target_path)

    excel_document = openpyxl.load_workbook(file_path)
    sheet_name = excel_document.get_sheet_names()[0]
    sheet = excel_document.get_sheet_by_name(sheet_name)

    print("Active Sheet:", sheet_name)

    # read excel file.
    sales_history = []
    total_price = 0
    last_idx = 0;
    flag = 1
    all_rows = sheet.rows
    for idx, row in enumerate(all_rows, start=-1):
        # loop handling 1
        if idx > 1000:
            flag = -1
            break

        last_idx = idx

        if idx < 1:
            continue

        sales_item = {}
        sales_item["no"] = str(idx)
        sales_item["date"] = str(row[0].value)
        sales_item["date"] = "/".join(sales_item["date"].split("-")[1:3])
        sales_item["date"] = sales_item["date"].split(" ")[0]
        # loop handling 2
        print(sales_item["date"], end=" ")
        if sales_item["date"] == "None" or sales_item["date"] == "":
            flag = 0
            break
        sales_item["work"] = row[3].value
        sales_item["content"] = ""
        # price column exception handling.
        if row[4].value is None:
            total_price += 0
            sales_item["price"] = "-"
        elif type(row[4].value) is str:
            total_price += 0
        else:
            sales_item["price"] = format(row[4].value, ",")
            print(sales_item["price"])
            total_price += row[4].value
        sales_item["tax"] = row[7].value
        sales_history.append(sales_item)

    print("Reading Data >>>")
    if flag == 1:
        print("\tSUCCESS: reading excel data")
    elif flag == 0:
        print("\tWARNING: for-loop's idx reaches until date is None.")
    else:
        print("\tERROR: for-loop's idx > 1000.")

    # write word file.
    total_price = format(total_price, ",")

    print("Sum >>>")
    print("\tTotal_Data:", last_idx, "건")
    print("\tTotal_Price:", total_price, "원")

    print("Write FIle >>>")
    flag = 1
    try:
        document = MailMerge(template_file)
        document.merge(
            number=sender[0],
            company=sender[1],
            name=sender[2],
            address=sender[3],
            call=sender[4],
            fax=sender[5],
            business=sender[6],
            category=sender[7]
        )
        document.merge(
            receiver=receiver,
            r_date=r_date,
            total_price=total_price
        )
        document.merge_rows('no', sales_history)
        document.write(target_path)
    except Exception as e:
        flag = 0
        print("\tError:", e)
    if flag == 1:
        print("\tSUCCESS:Writing file ->", target_path)
Пример #29
0
from __future__ import print_function
from mailmerge import MailMerge
from datetime import date

template = "Ms_Word_Table_Populate_Demo.docx"

document = MailMerge(template)
print(document.get_merge_fields())

sales_history = [{
    'prod_desc': 'Red Shoes',
    'price': '$10.00',
    'quantity': '2500',
    'total_purch': '$25,000.00'
}, {
    'prod_desc': 'Green Shirt',
    'price': '$20.00',
    'quantity': '10000',
    'total_purch': '$200,000.00'
}, {
    'prod_desc': 'Purple belt',
    'price': '$5.00',
    'quantity': '5000',
    'total_purch': '$25,000.00'
}]

document.merge_rows('prod_desc', sales_history)
document.write('test-output-table.docx')
print('DONE')
Пример #30
0
def merge(jsonData, generalData):

    name = generalData['file_name']
    organization = generalData['organization_name']
    project_type = generalData['project_type']
    reference = generalData['reference_number']
    our_reference = generalData['our_reference_number']
    date = generalData['date']
    datetimeobject = datetime.strptime(date, '%m/%d/%Y')
    date = datetimeobject.strftime('%B %d, %Y')
    exchange_rate = generalData['exchange_rate']
    notes = generalData['notes']

    note = []
    note.append('Please add 15% VAT')
    note.append('Price is valid for 45 days')
    note.append('All price is in Ethiopian Birr')
    note.append(
        'Delivery will be within 45 days after PO, advance and bank foreign currency approval'
    )
    note.append('Payment Term 50% advance and remaining amount after delivery')
    note.append('Installation is NOT part of this Quote')
    note.append(
        'If there is discrepancy in price calculation the unit price will prevail'
    )

    selectedNotes = []
    for x in generalData['vat']:
        selectedNotes.append(int(x))

    temp = [0, 1, 2, 3, 4, 5, 6]
    for selected in selectedNotes:
        temp[selected] = ''

    temp_note = ['', '', '', '', '', '', '']

    for y in [0, 1, 2, 3, 4, 5, 6]:
        if temp[y] == '':
            temp_note[y] = note[y]

    for elem in temp_note:
        if elem == '':
            temp_note.remove(elem)

    unit_market_price = []
    markup_percentage = []
    item_no = []
    part_no = []
    description = []
    quantity = []
    total = 0

    for i in range(len(jsonData)):
        ump = float(jsonData[i]['unit_market_price']) * float(exchange_rate)
        unit_market_price.append(ump)
        markup_percentage.append(jsonData[i]['markup_percentage'])
        item_no.append(jsonData[i]['item_no'])
        part_no.append(jsonData[i]['part_no'])
        description.append(jsonData[i]['description'])
        quantity.append(jsonData[i]['quantity'])

    for i in range(len(jsonData)):
        total = total + (calculateUitPrice(float(unit_market_price[i]),
                                           float(markup_percentage[i])) *
                         float(quantity[i]))

    total = str(total)

    template = 'master.docx'
    document = MailMerge(template)

    document.merge(
        organization=organization,
        project_type=project_type,
        reference=reference,
        our_ref_no=our_reference,
        date=date,
        notes=notes,
        total=total,
    )
    item_table = [{
        'item_no':
        str(data['item_no']),
        'part_no':
        str(data['part_no']),
        'description':
        str(data['description']),
        'quantity':
        str(data['quantity']),
        'unit_price':
        str(
            calculateUitPrice(
                (float(data['unit_market_price']) * float(exchange_rate)),
                float(data['markup_percentage']))),
        'total_price':
        str(
            calculateUitPrice(
                (float(data['unit_market_price']) * float(exchange_rate)),
                float(data['markup_percentage'])) * float(data['quantity']))
    } for data in jsonData]

    reminder_table = [{
        'reminder': temp_reminder
    } for temp_reminder in temp_note]

    document.merge_rows('item_no', item_table)
    document.merge_rows('reminder', reminder_table)
    document.write('documents/' + name + '.docx')

    now = datetime.now()

    record = Record(path=name + '.docx',
                    date=now,
                    organization=organization,
                    project_type=project_type)
    record.save()

    return
Пример #31
0
def validate_submit(request):
    data = {}
    try:
        x = {}

        x["z"] = json.loads(request.GET.get("all_data", None))
        for c in x["z"]:
            c["address"] = Home.objects.get(home_phone=c["address"]).address
        if date.today().month >= 10:
            x["year"] = twelve(int(date.today().year) + 1 - 1911)
        else:
            x["year"] = twelve(date.today().year - 1911)

        x["title"] = request.GET.get("title", None)
        # print(os.path.join(BASE_DIR, "files" ,"files","mode1.docx"))
        if request.GET.get("title", None) == "祈求值年太歲星君解除沖剋文疏":

            tpl = DocxTemplate(
                os.path.join(BASE_DIR, "files", "files", "mode1.docx"))
        else:
            tpl = DocxTemplate(
                os.path.join(BASE_DIR, "files", "files", "mode2.docx"))

        tpl.render(x)

        file_location = os.path.dirname(
            os.path.dirname(os.path.abspath(__file__)))
        find_folder = os.path.join(file_location, "output")
        find_yes_no = os.path.exists(find_folder)

        if not find_yes_no:
            os.makedirs(find_folder)

        find_x = ""
        find_y = ""
        while (True):
            random_string = str(uuid.uuid4())
            find_x = os.path.join(find_folder, random_string + ".docx")
            if not os.path.exists(find_x):
                find_y = os.path.join(find_folder, random_string + ".pdf")
                break
        tpl.save(find_x)

        pythoncom.CoInitialize()
        word = Dispatch('Word.Application')
        doc = word.Documents.Open(find_x)
        doc.SaveAs(find_y, FileFormat=17)
        doc.Close()
        word.Quit()
        os.system(find_y)

        #處理名字表
        name_list = json.loads(request.GET.get("name", None))

        use_word = MailMerge(
            os.path.join(BASE_DIR, "files", "files", "straight.docx"))
        use_word.merge_rows('name1', name_list)
        use_word.write(
            os.path.join(BASE_DIR, "files", "files", "ok_straight.docx"))
        use_word = MailMerge(
            os.path.join(BASE_DIR, "files", "files", "row.docx"))
        use_word.merge_rows('name1', name_list)
        use_word.write(os.path.join(BASE_DIR, "files", "files", "ok_row.docx"))

        data = {"result": "已經送出"}

    except Exception as e:
        data = {"result": str(e)}
        print("錯誤" + str(e))
    return JsonResponse(data)
Пример #32
0
               company_state_and_zip='Texas 100 002',
               company_phone_number='8756785989',
               delivery_charge='$150',
               total='$9150',
               benificiary_name='Tony Stark',
               benificiary_account_number='1234 5678 9101 1121',
               bank_name_and_address='Soft Bank, New York',
               ifsc_code='SB000921',
               upi_handle='@stark_sb',
               contact_name_1='Tony',
               contact_number_1='9876546789',
               contact_name_2='Stark',
               contact_number_2='8756789879')

purchase = [{
    's_no': '1',
    'product_name': 'Ark reactor',
    'quantity': '3',
    'rate': '$2000',
    'amount': '$6000'
}, {
    's_no': '2',
    'product_name': 'Mini Ark reactor',
    'quantity': '2',
    'rate': '$1500',
    'amount': '$3000'
}]

document.merge_rows('s_no', purchase)

document.write('result.docx')