def test(self): """ Test the case when Word splits a MergeField w:instrText into several pieces (Note the test document is a valid word document generated by Word 2007) """ document = MailMerge('tests/test_split_merge.docx') self.assertEquals(document.get_merge_fields(), set(['name_pinyin', 'name', 'semester', 'academic_year', 'date'])) with tempfile.NamedTemporaryFile() as outfile: document.write(outfile)
def mail_merge(self, company_name): #template1 = 'test1.docx' template2 = 'Executive_Summary2.docx' document = MailMerge(template2) print (document.get_merge_fields()) #merge fields #{'ZIP_Code', 'Address_Line_2', 'Country_or_Region', #'Address_Line_1', 'Company_Name', 'Title', # 'State', 'City', 'First_Name', 'Work_Phone', #'Email_Address', 'Home_Phone', 'Last_Name'} document.merge(Title = 'Mr', First_Name ='Joe', Last_Name = 'OShea', Company_Name = 'Principal Systems', Email_Address= '*****@*****.**', City = 'Dublin', State = 'Dublin', Work_Phone ='123333', Address_Line_1 ='56 Pembrooke road', Address_Line_2='Ballsbridge', Home_Phone='1234567', Country_or_Region='Ireland', ZIP_Code = 'Dublin6') output = company_name + '_output.docx' document.write(output) return output
def mail_merge(self, template, kwargs): company_name = kwargs.get('Company_Name', "default company_name") print('******',company_name) print('*******************', kwargs.items()) document = MailMerge(template) print (document.get_merge_fields()) #merge fields #{'ZIP_Code', 'Address_Line_2', 'Country_or_Region', #'Address_Line_1', 'Company_Name', 'Title', # 'State', 'City', 'First_Name', 'Work_Phone', #'Email_Address', 'Home_Phone', 'Last_Name'} document.merge(Title=kwargs.get('Title', "default title"), First_Name=kwargs.get('First_Name', "default fname"), Last_Name=kwargs.get('Last_Name', "default lname"), Company_Name=kwargs.get('Company_Name', "default company_name"), Email_Address=kwargs.get('Email_Address', "default email"), City=kwargs.get('City', "default city"), State=kwargs.get('State', "default state"), Work_Phone=kwargs.get('Work_Phone', "default Work Phone"), Address_Line_1=kwargs.get('Address_Line_1', "Address_Line_1"), Address_Line_2=kwargs.get('Address_Line_2', "default Address_Line_2"), Home_Phone=kwargs.get('Home_Phone', "Home_Phone"), Country_or_Region=kwargs.get('Country_or_Region', "default Country_or_Region"), ZIP_Code=kwargs.get('ZIP_Code ', "default ZIP_Code ")) output = company_name + '_output.docx' document.write(output) print(output, ' is ready') return output
def apply_mailmerge(self, context, filename="example.docx"): # Return a django request response with a docx download. docx = StringIO() mailmerge = MailMerge(self.get_full_path()) mailmerge.merge(context) mailmerge.write(docx) mailmerge.close() # return response docx.seek(0) response = HttpResponse(docx) response['Content-Disposition'] = 'attachment; filename={}'.format(filename) response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' return response
def test_paged(self): document = MailMerge(path.join(path.dirname(__file__), 'test_merge_list_paged.docx')) self.assertEqual(document.get_merge_fields(), {'fieldname'}) document.merge_list([ {'fieldname': "xyz"}, {'fieldname': "abc"}, {'fieldname': "2b v ~2b"}, ]) with tempfile.TemporaryFile() as outfile: document.write(outfile) expected_tree = ElementTree.fromstring( '<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="007B2B98"' ' w:rsidR="00507D2F" w:rsidRDefault="00651722"><w:r><w:t xml:space="preserve">This is a template for' ' the </w:t></w:r><w:r><w:t>xyz</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list test case</w:t>' '</w:r><w:r w:rsidR="00507D2F"><w:t>, page 1</w:t></w:r></w:p><w:p w:rsidR="00507D2F" w:rsidRDefault="00507D2F">' '<w:r><w:br w:type="page" /></w:r></w:p><w:p w:rsidP="007B2B98" w:rsidR="00EC3BBB" w:rsidRDefault="00507D2F"' ' w:rsidRPr="00651722"><w:r><w:lastRenderedPageBreak /><w:t xml:space="preserve">This is a template for the' ' </w:t></w:r><w:r><w:t>xyz</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list test case</w:t></w:r><w:r>' '<w:t>, page 2</w:t></w:r><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p>' '<w:sectPr w:rsidR="00EC3BBB" w:rsidRPr="00651722"><w:headerReference ns1:id="rId7" w:type="default" />' '<w:footerReference ns1:id="rId8" w:type="default" /><w:pgSz w:h="15840" w:w="12240" /><w:pgMar' ' w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1440" w:right="1440" w:top="1440"' ' /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body><w:br w:type="page" />' '<w:body><w:p w:rsidP="007B2B98" w:rsidR="00507D2F" w:rsidRDefault="00651722"><w:r><w:t xml:space="preserve"' '>This is a template for the </w:t></w:r><w:r><w:t>abc</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list' ' test case</w:t></w:r><w:r w:rsidR="00507D2F"><w:t>, page 1</w:t></w:r></w:p><w:p w:rsidR="00507D2F"' ' w:rsidRDefault="00507D2F"><w:r><w:br w:type="page" /></w:r></w:p><w:p w:rsidP="007B2B98" w:rsidR="00EC3BBB"' ' w:rsidRDefault="00507D2F" w:rsidRPr="00651722"><w:r><w:lastRenderedPageBreak /><w:t xml:space="preserve">' 'This is a template for the </w:t></w:r><w:r><w:t>abc</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list' ' test case</w:t></w:r><w:r><w:t>, page 2</w:t></w:r><w:bookmarkStart w:id="0" w:name="_GoBack" />' '<w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00EC3BBB" w:rsidRPr="00651722"><w:headerReference' ' ns1:id="rId7" w:type="default" /><w:footerReference ns1:id="rId8" w:type="default" /><w:pgSz w:h="15840"' ' w:w="12240" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1440"' ' w:right="1440" w:top="1440" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body>' '<w:br w:type="page" /><w:body><w:p w:rsidP="007B2B98" w:rsidR="00507D2F" w:rsidRDefault="00651722"><w:r>' '<w:t xml:space="preserve">This is a template for the </w:t></w:r><w:r><w:t>2b v ~2b</w:t></w:r><w:r><w:t' ' xml:space="preserve"> merge_list test case</w:t></w:r><w:r w:rsidR="00507D2F"><w:t>, page 1</w:t></w:r>' '</w:p><w:p w:rsidR="00507D2F" w:rsidRDefault="00507D2F"><w:r><w:br w:type="page" /></w:r></w:p><w:p' ' w:rsidP="007B2B98" w:rsidR="00EC3BBB" w:rsidRDefault="00507D2F" w:rsidRPr="00651722"><w:r>' '<w:lastRenderedPageBreak /><w:t xml:space="preserve">This is a template for the </w:t></w:r><w:r><w:t>2b' ' v ~2b</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list test case</w:t></w:r><w:r><w:t>, page 2</w:t>' '</w:r><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00EC3BBB"' ' w:rsidRPr="00651722"><w:headerReference ns1:id="rId7" w:type="default" /><w:footerReference ns1:id="rId8"' ' w:type="default" /><w:pgSz w:h="15840" w:w="12240" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0"' ' w:header="708" w:left="1440" w:right="1440" w:top="1440" /><w:cols w:space="708" /><w:docGrid' ' w:linePitch="360" /></w:sectPr></w:body></w:document>') self.assert_equal_tree(expected_tree, get_document_body_part(document).getroot())
def test(self): document = MailMerge('tests/test_macword2011.docx') self.assertEquals(document.get_merge_fields(), set(['first_name', 'last_name', 'country', 'state', 'postal_code', 'date', 'address_line', 'city'])) document.merge(first_name='Bouke', last_name='Haarsma', country='The Netherlands', state=None, postal_code='9723 ZA', city='Groningen', address_line='Helperpark 278d', date='May 22nd, 2013') with tempfile.NamedTemporaryFile() as outfile: document.write(outfile)
def test(self): document = MailMerge('tests/test_winword2010.docx') self.assertEquals(document.get_merge_fields(), set(['Titel', 'Voornaam', 'Achternaam', 'Adresregel_1', 'Postcode', 'Plaats', 'Provincie', 'Land_of_regio'])) document.merge(Voornaam='Bouke', Achternaam='Haarsma', Land_of_regio='The Netherlands', Provincie=None, Postcode='9723 ZA', Plaats='Groningen', Adresregel_1='Helperpark 278d', Titel='dhr.') with tempfile.NamedTemporaryFile() as outfile: document.write(outfile.name)
def test(self): document = MailMerge(path.join(path.dirname(__file__), 'test_macword2011.docx')) self.assertEqual(document.get_merge_fields(), set(['first_name', 'last_name', 'country', 'state', 'postal_code', 'date', 'address_line', 'city'])) document.merge(first_name='Bouke', last_name='Haarsma', country='The Netherlands', state=None, postal_code='9723 ZA', city='Groningen', address_line='Helperpark 278d', date='May 22nd, 2013') with tempfile.TemporaryFile() as outfile: document.write(outfile) expected_tree = etree.fromstring( '<w:document xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ' 'xmlns:ns1="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w="http://schemas' '.openxmlformats.org/wordprocessingml/2006/main" mc:Ignorable="w14 wp14">' '<w:body><w:p ns1:paraId="25CDEC86" ns1:textId="77777777" ' 'w:rsidR="00FB567A" w:rsidRDefault="00541684"><w:r><w:t>Bouke</w:t></w:r><w:r w:rsidR="00916690"><w:t ' 'xml:space="preserve"> </w:t></w:r><w:r><w:t>Haarsma</w:t></w:r></w:p><w:p ns1:paraId="67F7A559" ' 'ns1:textId="77777777" w:rsidR="00916690" w:rsidRDefault="00541684"><w:r><w:t>Helperpark ' '278d</w:t></w:r></w:p><w:p ns1:paraId="228F2AEA" ns1:textId="77777777" w:rsidR="00916690" ' 'w:rsidRDefault="00541684"><w:r><w:t>9723 ZA</w:t></w:r><w:r><w:t xml:space="preserve"> ' '</w:t></w:r><w:r><w:t>Groningen</w:t></w:r><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd ' 'w:id="0" /><w:r w:rsidR="00916690"><w:t xml:space="preserve"> </w:t></w:r><w:r><w:t /></w:r><w:r ' 'w:rsidR="00916690"><w:t xml:space="preserve"> </w:t></w:r><w:r><w:t>The ' 'Netherlands</w:t></w:r></w:p><w:p ns1:paraId="696E15D7" ns1:textId="77777777" w:rsidR="00916690" ' 'w:rsidRDefault="00916690" /><w:p ns1:paraId="3F48DA35" ns1:textId="77777777" w:rsidR="00916690" ' 'w:rsidRDefault="00916690" /><w:p ns1:paraId="68E7FBD1" ns1:textId="77777777" w:rsidR="00916690" ' 'w:rsidRDefault="00916690"><w:r><w:t xml:space="preserve">Groningen, </w:t></w:r><w:r><w:t>May 22nd, ' '2013</w:t></w:r><w:r><w:t>,</w:t></w:r></w:p><w:p ns1:paraId="26B47597" ns1:textId="77777777" ' 'w:rsidR="00916690" w:rsidRDefault="00916690" /><w:p ns1:paraId="740FF493" ns1:textId="77777777" ' 'w:rsidR="00916690" w:rsidRDefault="00916690" /><w:p ns1:paraId="232699A0" ns1:textId="77777777" ' 'w:rsidR="00916690" w:rsidRDefault="00916690"><w:r><w:t xml:space="preserve">Dear ' '</w:t></w:r><w:r><w:t>Bouke</w:t></w:r><w:r><w:t>,</w:t></w:r></w:p><w:p ns1:paraId="1AE04A19" ' 'ns1:textId="77777777" w:rsidR="00916690" w:rsidRDefault="00916690" /><w:p ns1:paraId="298752B0" ' 'ns1:textId="77777777" w:rsidR="00916690" w:rsidRDefault="00916690" /><w:p ns1:paraId="477BE6DB" ' 'ns1:textId="77777777" w:rsidR="00916690" w:rsidRDefault="00916690"><w:r><w:t>I hope this message finds ' 'you well.</w:t></w:r></w:p><w:p ns1:paraId="77542CE2" ns1:textId="77777777" w:rsidR="00916690" ' 'w:rsidRDefault="00916690" /><w:p ns1:paraId="734AC552" ns1:textId="77777777" w:rsidR="00916690" ' 'w:rsidRDefault="00916690" /><w:p ns1:paraId="1680D84C" ns1:textId="77777777" w:rsidR="00916690" ' 'w:rsidRDefault="00916690"><w:r><w:t>Kind regards,</w:t></w:r></w:p><w:p ns1:paraId="67F698AC" ' 'ns1:textId="77777777" w:rsidR="00916690" w:rsidRDefault="00916690" /><w:p ns1:paraId="7A4C001B" ' 'ns1:textId="77777777" w:rsidR="00916690" w:rsidRDefault="00916690"><w:r><w:t>docx-mailmerge' '.</w:t></w:r></w:p><w:sectPr w:rsidR="00916690" w:rsidSect="00CA5A66"><w:pgSz w:h="16840" w:w="11900" ' '/><w:pgMar w:bottom="1417" w:footer="708" w:gutter="0" w:header="708" w:left="1417" w:right="1417" ' 'w:top="1417" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body></w:document>') self.assert_equal_tree(expected_tree, list(document.parts.values())[0].getroot())
def test_pages(self): document = MailMerge(path.join(path.dirname(__file__), 'test_merge_pages.docx')) self.assertEqual(document.get_merge_fields(), {'fieldname'}) document.merge_pages([ {'fieldname': "xyz"}, {'fieldname': "abc"}, {'fieldname': "2b v ~2b"}, ]) with tempfile.TemporaryFile() as outfile: document.write(outfile) expected_tree = etree.fromstring('<w:document xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ns1="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" mc:Ignorable="w14 wp14"><w:body><w:p w:rsidP="007B2B98" w:rsidR="00EC3BBB" w:rsidRDefault="00651722" w:rsidRPr="00651722"><w:r><w:t xml:space="preserve">This is a template for the </w:t></w:r><w:r><w:t>xyz</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list test case</w:t></w:r><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00EC3BBB" w:rsidRPr="00651722"><w:headerReference ns1:id="rId7" w:type="default" /><w:footerReference ns1:id="rId8" w:type="default" /><w:pgSz w:h="15840" w:w="12240" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1440" w:right="1440" w:top="1440" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body><w:br w:type="page" /><w:body><w:p w:rsidP="007B2B98" w:rsidR="00EC3BBB" w:rsidRDefault="00651722" w:rsidRPr="00651722"><w:r><w:t xml:space="preserve">This is a template for the </w:t></w:r><w:r><w:t>abc</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list test case</w:t></w:r><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00EC3BBB" w:rsidRPr="00651722"><w:headerReference ns1:id="rId7" w:type="default" /><w:footerReference ns1:id="rId8" w:type="default" /><w:pgSz w:h="15840" w:w="12240" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1440" w:right="1440" w:top="1440" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body><w:br w:type="page" /><w:body><w:p w:rsidP="007B2B98" w:rsidR="00EC3BBB" w:rsidRDefault="00651722" w:rsidRPr="00651722"><w:r><w:t xml:space="preserve">This is a template for the </w:t></w:r><w:r><w:t>2b v ~2b</w:t></w:r><w:r><w:t xml:space="preserve"> merge_list test case</w:t></w:r><w:bookmarkStart w:id="0" w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:sectPr w:rsidR="00EC3BBB" w:rsidRPr="00651722"><w:headerReference ns1:id="rId7" w:type="default" /><w:footerReference ns1:id="rId8" w:type="default" /><w:pgSz w:h="15840" w:w="12240" /><w:pgMar w:bottom="1440" w:footer="708" w:gutter="0" w:header="708" w:left="1440" w:right="1440" w:top="1440" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body></w:document>') # noqa self.assert_equal_tree(expected_tree, get_document_body_part(document).getroot())
def test(self): document = MailMerge(path.join(path.dirname(__file__), 'test_winword2010.docx')) self.assertEqual(document.get_merge_fields(), set(['Titel', 'Voornaam', 'Achternaam', 'Adresregel_1', 'Postcode', 'Plaats', 'Provincie', 'Land_of_regio'])) document.merge(Voornaam='Bouke', Achternaam='Haarsma', Land_of_regio='The Netherlands', Provincie=None, Postcode='9723 ZA', Plaats='Groningen', Adresregel_1='Helperpark 278d', Titel='dhr.') with tempfile.NamedTemporaryFile() as outfile: document.write(outfile) expected_tree = ElementTree.fromstring( '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p ' 'w:rsidR="00886208" w:rsidRDefault="00886208"><w:r><w:t>dhr.</w:t></w:r><w:r ' 'w:rsidRPr="00886208"><w:rPr><w:lang w:val="nl-NL" /></w:rPr><w:t xml:space="preserve"> ' '</w:t></w:r><w:r><w:t>Bouke</w:t></w:r><w:r w:rsidRPr="00886208"><w:rPr><w:lang w:val="nl-NL" ' '/></w:rPr><w:t xml:space="preserve"> </w:t></w:r><w:r><w:t>Haarsma</w:t></w:r></w:p><w:p ' 'w:rsidR="00886208" w:rsidRDefault="00886208" w:rsidRPr="00886208"><w:pPr><w:rPr><w:lang w:val="nl-NL" ' '/></w:rPr></w:pPr><w:r><w:t>Helperpark 278d</w:t></w:r></w:p><w:p w:rsidR="00886208" ' 'w:rsidRDefault="00886208"><w:r><w:t>9723 ZA</w:t></w:r><w:r w:rsidRPr="00886208"><w:rPr><w:lang ' 'w:val="nl-NL" /></w:rPr><w:t xml:space="preserve"> </w:t></w:r><w:r><w:t>Groningen</w:t></w:r><w:r ' 'w:rsidRPr="00886208"><w:rPr><w:lang w:val="nl-NL" /></w:rPr><w:t xml:space="preserve"> ' '</w:t></w:r><w:r><w:t /></w:r><w:r w:rsidRPr="00886208"><w:rPr><w:lang w:val="nl-NL" /></w:rPr><w:t ' 'xml:space="preserve"> </w:t></w:r><w:r><w:t>The Netherlands</w:t></w:r></w:p><w:p w:rsidR="00886208" ' 'w:rsidRDefault="00886208" /><w:p w:rsidR="00886208" w:rsidRDefault="00886208"><w:r><w:t>Groningen,' '</w:t></w:r></w:p><w:p w:rsidR="00886208" w:rsidRDefault="00886208"><w:bookmarkStart w:id="0" ' 'w:name="_GoBack" /><w:bookmarkEnd w:id="0" /></w:p><w:p w:rsidR="004D7161" ' 'w:rsidRDefault="00886208"><w:r><w:t xml:space="preserve">Dear ' '</w:t></w:r><w:r><w:t>Bouke</w:t></w:r><w:r><w:t>,</w:t></w:r></w:p><w:p w:rsidR="00886208" ' 'w:rsidRDefault="00886208" /><w:p w:rsidR="00886208" w:rsidRDefault="00886208"><w:r><w:t>I hope this ' 'document from WinWord 2010 finds you well.</w:t></w:r></w:p><w:p w:rsidR="00886208" ' 'w:rsidRDefault="00886208" /><w:p w:rsidR="00886208" w:rsidRDefault="00886208"><w:r><w:t>Kind regards,' '</w:t></w:r></w:p><w:p w:rsidR="00886208" w:rsidRDefault="00886208" ' 'w:rsidRPr="00886208"><w:pPr><w:rPr><w:lang w:val="en-US" /></w:rPr></w:pPr><w:proofErr ' 'w:type="spellStart" /><w:r><w:t>docx-mailmerge</w:t></w:r><w:proofErr w:type="spellEnd" /><w:r><w:t>' '.</w:t></w:r></w:p><w:sectPr w:rsidR="00886208" w:rsidRPr="00886208"><w:pgSz w:h="16838" w:w="11906" ' '/><w:pgMar w:bottom="1417" w:footer="708" w:gutter="0" w:header="708" w:left="1417" w:right="1417" ' 'w:top="1417" /><w:cols w:space="708" /><w:docGrid w:linePitch="360" /></w:sectPr></w:body></w:document>') self.assert_equal_tree(expected_tree, list(document.parts.values())[0].getroot())
from __future__ import print_function from mailmerge import MailMerge import datetime as date template = "Amnova Quote Template.docx" 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',
def response_sthlm(bidragcontainer): per_diem = 35 # Amount per scout per day 2021 h1_end = datetime(2021, 5, 31, 23, 59) bidrag = bidragcontainer.bidrag persons = bidragcontainer.persons nr_persons = bidragcontainer.nr_persons_total persons = persons[:nr_persons] start = datetime.strptime(bidrag.dateFrom, DATE_FORMAT) end = datetime.strptime(bidrag.dateTo, DATE_FORMAT) nr_days = (end - start).days + 1 if bidrag.zipCode != "": zcParts = bidrag.zipCode.split() postnr = "".join(zcParts[:-1]) # remove possible space in zip code postort = zcParts[-1] today = date.today() data = { 'organisationsnummer': bidrag.organisationsnummer, 'kontonummer': bidrag.kontonummer, 'kundnummer': bidrag.foreningsID, 'foreningsnamn': bidrag.kar, 'epost': bidrag.email, 'ledare': bidrag.contact, 'ledartelefon': bidrag.contactphone, 'ledaremail': bidrag.contactemail, 'lov': u'X' if bidrag.hikeduringbreak else u'\u2610', 'helg': u'\u2610' if bidrag.hikeduringbreak else u'X', 'lagerplats': bidrag.site, 'startdatum': bidrag.dateFrom, 'slutdatum': bidrag.dateTo, 'datum': today.strftime(DATE_FORMAT), 'dag': str(today.day), 'manad': str(today.month), 'ordforande': bidrag.firmatecknare, 'ordforandetelefon': bidrag.firmatecknartelefon, 'ordforandeemail': bidrag.firmatecknaremail, 'adress': bidrag.address, 'postnr': postnr, 'postort': postort, 'bankkonto': bidrag.account, 'antalmedlemmar': str(bidragcontainer.nr_young_persons), 'antaldagar': str(nr_days), # Should be total number of days 'summa': str(bidrag.days * per_diem) + ",00", 'H1': u'\u2610' if h1_end <= end else u'X', 'H2': u'\u2610' if h1_end > end else u'X' } period_data = generate_sthlm_period_data(today.year, today.month, today.day) data.update(period_data) persons_per_page = 25 nr_pages, rest = divmod(nr_persons, persons_per_page) if rest > 0: nr_pages += 1 pages = [] for page_nr in range(nr_pages): page_data = copy.deepcopy(data) persons_in_page = persons[page_nr * persons_per_page:(page_nr + 1) * persons_per_page] for i, person in enumerate(persons_in_page): nr = i + 1 page_data['namn%d' % nr] = person.name page_data['pa%d' % nr] = person.postal_address page_data['ar%d' % nr] = str(person.year) if person.days != nr_days: page_data['ad%d' % nr] = str(person.days) pages.append(page_data) document = MailMerge('templates/lagerbidragsmall_sthlm_2021.docx') document.merge_pages(pages) bytesIO = io.BytesIO() document.write(bytesIO) resultbytes = bytesIO.getvalue() doc_name = "Lagerbidrag_%s_%s_%s.docx" % (bidrag.site, bidrag.dateFrom, bidrag.dateTo) ascii_doc_name = doc_name.encode('ascii', 'ignore') response = make_response(resultbytes) response.headers[ 'Content-Type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' response.headers[ 'Content-Disposition'] = 'attachment; filename=' + urllib.quote( ascii_doc_name) return response
if template == "Prueba1.docx": materia = "recargo prestaciones" elif template == "Prueba5.docx": materia = "recargo prestaciones" elif template == "Extincion retraso pago.docx": materia = "extincion contrato" elif template == "Extincion falta de pago.docx": materia = "extincion contrato" elif template == "Extincion modificacion sustancial.docx": materia = "extincion contrato" else: materia = "recargo prestaciones" # uso del template elegido document = MailMerge(template) # creación de función para ver si la opción de indemnización ha sido seleccionada y rellenada, en caso contrario no hace nada def indemnizacionsiono(): if entry_var23.get(): return indemnizacion_despido_prueba(str(entry_var21.get()), str(entry_var23.get()), str(today)) else: valor0 = 0 return valor0 # crear funcion de mayusculas y minusculas actor def actorcapitalizacion():
print(r.status_code) #se crea un diccionario con el json que viene del response para la cedula consultada dict_emp = {} #esto lo que va a hacer es quitar el primer elemento del diccionario para que solo quede la info que viene del web service dict_emp = r.json()[-1] # imprimimos el contenido para ver que informacion nos trajo print(dict_emp) # guardamos el template de la constancia en la variable template template = "Constancia_salarial_template.docx" #Creamos un documento mailmerge que contiene la informacion del template document = MailMerge(template) #imprimimos el contenido del objeto para ver todos los campos a llenar que contiene print(document.get_merge_fields()) #Funcion para insertar info en Doc de word #Funcion para calcular el salario Neto, recibe el salario bruto por parametro #calculo de renta: #817 - 1,226: 10% #1,226 - 2,103: 15% #2,103 - 4,205: 20% #4,205+ : 25% def calcSalarioNeto(salarioBruto): salarioNeto = 0
def test(self): document = MailMerge( path.join(path.dirname(__file__), 'test_issue8.docx')) self.assertEqual(document.get_merge_fields(), {'testfield'})
def main(self): list_columns = ['Global ID', 'Local Name', 'Status', 'Notes'] df_list = pd.DataFrame(columns=list_columns) self.read_files() for n_idx, n_row in self.df_data.iterrows(): lv_template = self.template document_1 = MailMerge(self.path + lv_template) try: dict = { "Global_ID": str(n_row['Global ID']), "English_Name": str(n_row['English Name']), "Local_Name": str(n_row['Local Name']), "Department": str(n_row['Department']), "Performance_Rating": n_row['Performance Rating'], "Bonus_Amount": '{:.2f}'.format(n_row['Bonus_Amount']), "Individual_Modifier": '{:.2f}'.format(n_row['Individual Modifier']), # "Individual_Modifier": '{:.2f}%'.format(n_row['Individual Modifier']), "Business_Modifier": '{:.2f}'.format(n_row['Business Modifier']), "Payout_Rate": '{:.2f}'.format(n_row['Payout Rate']), } document_1.merge(**dict) file_path = self.path + 'xlsx/' if not os.path.exists(file_path): os.makedirs(file_path) # filename lv_name = self.prefix + str( n_row['Global ID']) + '_' + n_row['Local Name'] file_docx = self.path + 'xlsx/' + lv_name + '.docx' document_1.write(file_docx) # time.sleep(1) file_path = self.path + 'pdf' + '/' + n_row['HRBP'] + '/' if not os.path.exists(file_path): os.makedirs(file_path) if n_row['Division'] != "": file_path = file_path + n_row['Division'] + '/' if not os.path.exists(file_path): os.makedirs(file_path) if n_row['Division2'] != "": file_path = file_path + n_row['Division2'] + '/' if not os.path.exists(file_path): os.makedirs(file_path) if n_row['Division3'] != "": file_path = file_path + n_row['Division3'] + '/' if not os.path.exists(file_path): os.makedirs(file_path) file_pdf = file_path + lv_name + '.pdf' convert(file_docx, file_pdf, keep_active=True) print('Success:', n_row['Local Name'], n_idx + 1) document_1.close() emp_line = [n_row['Global ID'], n_row['Local Name'], 'S', ''] df_list = df_list.append(pd.Series(emp_line, index=list_columns), ignore_index=True) except Exception as e: print('Failed to generate file for line ', n_idx + 1, e) emp_line = [n_row['Global ID'], n_row['Local Name'], 'E', ''] df_list = df_list.append(pd.Series(emp_line, index=list_columns), ignore_index=True) df_list.to_csv(self.path + 'log.csv')
def replace_mailing_merge_and_convert_to_pdf(self): with open(self.data_mailingMerge) as f: data = json.load(f)['data'] len_data = len(data) if not os.path.exists(self.output_Word): os.makedirs(self.output_Word) if not os.path.exists(self.output_PDF): os.makedirs(self.output_PDF) if self.multiple_files: for index, input in enumerate(data): print('creating {}/{} ...'.format(index, len_data)) document = MailMerge(self.word_template) document.merge(**input) word_output = os.path.join( self.output_Word, self.fileName_prefix + str(index + 1) + self.word_extension) document.write(word_output) # convert to PDF if self.convert_to_pdf: subprocess.check_output([ '/Applications/LibreOffice.app/Contents/MacOS/soffice', '--convert-to', 'pdf', '--outdir', self.output_PDF, word_output ]) else: print("creating one file containing {} mails...".format(len_data)) document = MailMerge(self.word_template) document.merge_pages(data) word_output = os.path.join( self.output_Word, self.fileName_prefix + self.word_extension) document.write(word_output) # convert to PDF if self.convert_to_pdf: subprocess.check_output([ '/Applications/LibreOffice.app/Contents/MacOS/soffice', '--convert-to', 'pdf', '--outdir', self.output_PDF, word_output ]) print('replace_mailingMerge_and_convertToPDF is done !')
def get_values_adolecente(): template = MailMerge("moulage_temp.docx") name = str(input("Nom et prénom du patient: ")) age = str(input("Age du patient: ")) overjet = float(input("Overjet: ")) overbite = float(input("Overbite: ")) ###################### Superieure _11 = float(input("diam MD de la 11: ")) _12 = float(input("diam MD de la 12: ")) _13 = float(input("diam MD de la 13: ")) _14 = float(input("diam MD de la 14: ")) _15 = float(input("diam MD de la 15: ")) _21 = float(input("diam MD de la 21: ")) _22 = float(input("diam MD de la 22: ")) _23 = float(input("diam MD de la 23: ")) _24 = float(input("diam MD de la 24: ")) _25 = float(input("diam MD de la 25: ")) _16 = float(input("diam MD de la 16: ")) l_sup_m = float(input("longueur d'arcade supérieure: ")) d4g4_sup_m = float(input("D4G4 supérieure: ")) d6g6_sup_m = float(input("D6G6 supérieure: ")) l_base = float(input("Longeur de base maxillaire: ")) if (_14 + _15 + _24 + _25 == 0): ED_sup = float(input("Espace disponible supérieure: ")) - 1.8 if (_14 + _15 == 0) and (_24 + _25 != 0): ED_sup = float(input("Espace disponible supérieure: ")) - 0.9 if (_14 + _15 != 0) and (_24 + _25 != 0): ED_sup = float(input("Espace disponible supérieure: ")) ####################### Inferieure _31 = float(input("diam MD de la 31: ")) _32 = float(input("diam MD de la 32: ")) _33 = float(input("diam MD de la 33: ")) _34 = float(input("diam MD de la 34: ")) _35 = float(input("diam MD de la 35: ")) _41 = float(input("diam MD de la 41: ")) _42 = float(input("diam MD de la 42: ")) _43 = float(input("diam MD de la 43: ")) _44 = float(input("diam MD de la 44: ")) _45 = float(input("diam MD de la 45: ")) l_inf_m = float(input("longueur d'arcade inférieure: ")) d4g4_inf_m = float(input("D4G4 inférieure: ")) d6g6_inf_m = float(input("D6G6 inférieure: ")) if (_34 + _35 + _44 + _45 == 0): ED_inf = float(input("Espace disponible supérieure: ")) - 3.4 if (_34 + _35 == 0) and (_44 + _45 != 0): ED_inf = float(input("Espace disponible supérieure: ")) - 1.7 if (_34 + _35 != 0) and (_44 + _45 != 0): ED_inf = float(input("Espace disponible supérieure: ")) ####################### Calcules if _13 == 0 and _23 != 0: _13 == _23 if _23 == 0 and _13 != 0: _23 == _13 if _14 == 0 and _24 != 0: _14 == _24 if _24 == 0 and _14 != 0: _24 == _14 if _15 == 0 and _25 != 0: _15 == _25 if _25 == 0 and _15 != 0: _25 == _15 EN_inf_TJ = _31 + _32 + _33 + _34 + _35 + _41 + _42 + _43 + _44 + _45 EN_sup_TJ = _11 + _12 + _13 + _14 + _15 + _21 + _22 + _23 + _24 + _25 p10 = (_11 + _14 + _16) * 2.84 p14 = (_11 + _14 + _16) * 4.4 l_sup_t = round((p10 / 2.58), 2) l_inf_t = round((p10 / 3.10), 2) d4g4_sup_t = round((p14 * 0.32), 2) d6g6_sup_t = round((p14 * 0.4), 2) d4g4_inf_t = round((p10 / 2.32), 2) d6g6_inf_t = round((p10 / 1.76), 2) ddm_sup = round((ED_sup - EN_sup_TJ), 2) ddm_inf = round((ED_inf - EN_inf_TJ), 2) ####################### Merge template.merge(name=name, age=age, overbite=str(overbite), overjet=str(overjet), p10=str(p10), p14=str(p14), d4g4_sup_m=str(d4g4_sup_m), d4g4_sup_t=str(d4g4_sup_t), d6g6_sup_m=str(d6g6_sup_m), d6g6_sup_t=str(d6g6_sup_t), l_sup_m=str(l_sup_m), l_sup_t=str(l_sup_t), l_base=str(l_base), ddm_sup=str(ddm_sup)) template.merge(d4g4_inf_m=str(d4g4_inf_m), d4g4_inf_t=str(d4g4_inf_t), d6ag6_inf_m=str(d6g6_inf_m), d6g6_inf_t=str(d6g6_inf_t), l_inf_m=str(l_inf_m), l_inf_t=str(l_inf_t), ddm_inf=str(ddm_inf)) template.write("{}.docx".format(name))
def get_values_mixte(): template = MailMerge("moulage_temp.docx") name = str(input("Nom et prénom du patient: ")) age = str(input("Age du patient: ")) overjet = float(input("Overjet: ")) overbite = float(input("Overbite: ")) ###################### Superieure _11 = float(input("diam MD de la 11: ")) _12 = float(input("diam MD de la 12: ")) _21 = float(input("diam MD de la 21: ")) _22 = float(input("diam MD de la 22: ")) _16 = float(input("diam MD de la 16: ")) l_sup_m = float(input("longueur d'arcade supérieure: ")) d4g4_sup_m = float(input("D4G4 supérieure: ")) d6g6_sup_m = float(input("D6G6 supérieure: ")) l_base = float(input("Longeur de base maxillaire: ")) ED_sup = float(input("Espace disponible supérieure: ")) - 1.8 ####################### Inferieure _31 = float(input("diam MD de la 31: ")) _32 = float(input("diam MD de la 32: ")) _41 = float(input("diam MD de la 41: ")) _42 = float(input("diam MD de la 42: ")) l_inf_m = float(input("longueur d'arcade inférieure: ")) d4g4_inf_m = float(input("D4G4 inférieure: ")) d6g6_inf_m = float(input("D6G6 inférieure: ")) ED_inf = float(input("Espace disponible inférieure: ")) - 3.4 ####################### Calcules EN_inf_TJ = 2 * (_31 + _32 + _41 + _42) + 21 EN_sup_TJ = (_11 + _12 + _21 + _22) + (_31 + _32 + _41 + _42) + 22 p10 = (_11 + _16) * 3.85 p14 = (_11 + _16) * 5.95 l_sup_t = round((p10 / 2.58), 2) l_inf_t = round((p10 / 3.10), 2) d4g4_sup_t = round((p14 * 0.32), 2) d6g6_sup_t = round((p14 * 0.4), 2) d4g4_inf_t = round((p10 / 2.32), 2) d6g6_inf_t = round((p10 / 1.76), 2) ddm_sup = ED_sup - EN_sup_TJ ddm_inf = ED_inf - EN_inf_TJ ####################### Merge template.merge(name=name, age=age, overbite=str(overbite), overjet=str(overjet), p10=str(p10), p14=str(p14), d4g4_sup_m=str(d4g4_sup_m), d4g4_sup_t=str(d4g4_sup_t), d6g6_sup_m=str(d6g6_sup_m), d6g6_sup_t=str(d6g6_sup_t), l_sup_m=str(l_sup_m), l_sup_t=str(l_sup_t), l_base=str(l_base), ddm_sup=str(ddm_sup)) template.merge(d4g4_inf_m=str(d4g4_inf_m), d4g4_inf_t=str(d4g4_inf_t), d6g6_inf_m=str(d6g6_inf_m), d6g6_inf_t=str(d6g6_inf_t), l_inf_m=str(l_inf_m), l_inf_t=str(l_inf_t), ddm_inf=str(ddm_inf)) template.write("{}.docx".format(name))
from __future__ import print_function from mailmerge import MailMerge docfile = 'resume_maker/my_resume.docx' document = MailMerge(template) print(document.get_merge_fields()) document.merge(test='test sucess') document.write('test-output.docx')
# -*- coding: utf-8 -*- """ Created on Sat Nov 16 17:46:10 2019 @author: Kratik Saxena """ from mailmerge import MailMerge from datetime import date #df=pd.read_csv('PythonExport.csv') #print(df.iloc[0,1]) template = "TEMPLATE.docx" document = MailMerge(template) print(document.get_merge_fields()) di={"Name":"Sherni"} document.merge( X_PAT_1_NUMBER ='Gold', X_PAT_2_NUMBER ='Springfield', X_PAT_3_NUMBER = 'US', X_PAT_1_TITLE = 'abc', X_PAT_2_TITLE = 'bca', X_PAT_3_TITLE = 'cab', X_PAT_1_ASSIGNEE = 'xyz', X_PAT_2_ASSIGNEE = 'yzx', X_PAT_3_ASSIGNEE = 'zxy', X_PAT_1_PUBDATE = 'qwe', X_PAT_2_PUBDATE = 'weq', X_PAT_3_PUBDATE = 'eqw', X_PAT_1_APPDATE = 'alsmj',
def main(self): list_columns = ['Global ID', 'Employee Name', 'Status', 'Notes'] df_list = pd.DataFrame(columns=list_columns) self.read_files() for n_idx, n_row in self.df_data.iterrows(): if len(str(n_row['Target Move Date'])) > 0: if n_row['Template'] == 'fix': lv_template = self.template_fix else: lv_template = self.template document_1 = MailMerge(self.path + lv_template) # print(document_1.get_merge_fields()) # isinstance(['Target Move Date'], datetime): try: lv_target_cn = n_row['Target Move Date'].strftime( "%Y年%m月%d日") lv_target_en = n_row['Target Move Date'].strftime( "%d/%m/%Y") lv_start_en = n_row['Start date of ZF Service'].strftime( "%d/%m/%Y") lv_start_cn = n_row['Start date of ZF Service'].strftime( "%Y年%m月%d日") if n_row['Template'] == 'fix': lv_contract_end = '' lv_contract_end_cn = '' else: lv_contract_end = n_row[ 'Latest Contract ending date'].strftime("%d/%m/%Y") lv_contract_end_cn = n_row[ 'Latest Contract ending date'].strftime( "%Y年%m月%d日") print(lv_contract_end_cn) # lv_contract_end = n_row['Latest Contract ending date'].to_timestamp().strftime("%d/%m/%Y") # lv_date = time.localtime(time.mktime(time.strptime(n_row['Latest Contract ending date'],'%Y-%m-%d'))) # # print(lv_date) # # lv_contract_end = time.strptime("%d/%m/%Y %H:%M:%S",lv_date) # # print(lv_contract_end) # # lv_contract_end_cn = n_row['Latest Contract ending date'].to_timestamp().strftime("%Y年%m月%d日") # # print(lv_contract_end_cn) # lv_contract_end_cn = '至' + str(lv_date.tm_year) +'年' + str(lv_date.tm_mon) + '月' + str(lv_date.tm_mday) + '日止' # lv_contract_end = 'lasts until ' + str(lv_date.tm_mday) + '/' + str(lv_date.tm_mon) + '/' + str(lv_date.tm_year) dict = { "Chinese_Name": str(n_row['Chinese Name']), "Employee_Name": str(n_row['Employee Name']), "National_ID": str(n_row['National ID']), # "Start_date_of_ZF_Service": str(n_row['Start date of ZF Service']), # "Target_Move_Date": str(n_row['Target Move Date']) "Target_Move_Date": lv_target_en, "Target_Move_Date_CN": lv_target_cn, "Start_date_of_ZF_Service": lv_start_en, "Start_date_of_ZF_Service_CN": lv_start_cn, "Contract_End_CN": lv_contract_end_cn, "Contract_End": lv_contract_end, } document_1.merge(**dict) file_path = self.path + 'xlsx/' if not os.path.exists(file_path): os.makedirs(file_path) lv_name = self.prefix + n_row[ 'Division for list'] + '_' + n_row['Employee Name'] file_docx = self.path + 'xlsx/' + lv_name + '.docx' document_1.write(file_docx) # time.sleep(1) file_path = self.path + 'pdf' + '/' + n_row['HR BP2'] + '/' if not os.path.exists(file_path): os.makedirs(file_path) if n_row['Mark'] != "": file_path = file_path + n_row['Mark'] + '/' if not os.path.exists(file_path): os.makedirs(file_path) # file_pdf = file_path + 'pdf/' + lv_name + '.pdf' file_pdf = file_path + lv_name + '.pdf' # file_pdf = self.path + 'pdfs/' + n_row['姓名'] + '.pdf' # self.generate_pdf(file_docx,file_pdf) convert(file_docx, file_pdf, keep_active=True) print('Success:', n_row['Employee Name'], n_idx + 1) document_1.close() emp_line = [ n_row['Globle ID'], n_row['Employee Name'], 'S', '' ] df_list = df_list.append(pd.Series(emp_line, index=list_columns), ignore_index=True) except Exception as e: print('Failed to generate file for line ', n_idx + 1, e) emp_line = [ n_row['Globle ID'], n_row['Employee Name'], 'E', '' ] df_list = df_list.append(pd.Series(emp_line, index=list_columns), ignore_index=True) df_list.to_csv(self.path + 'log.csv')
def write_file(self): feedbacks = [] feedback_secretary = Feedback() feedback_lib = Feedback() feedback_fin = Feedback() feedback_coord = Feedback() feedback_napes = Feedback() feedback_dir = Feedback() feedback_caa = Feedback() for feedback in self.solicitation.feedbacks.all(): if feedback.feedbacker.usuario.is_secretary: feedback_secretary = feedback elif feedback.feedbacker.usuario.is_library: feedback_lib = feedback elif feedback.feedbacker.usuario.is_finance: feedback_fin = feedback elif feedback.feedbacker.usuario.is_coordination: feedback_coord = feedback elif feedback.feedbacker.usuario.is_napes: feedback_napes = feedback elif feedback.feedbacker.usuario.is_director: feedback_dir = feedback elif feedback.feedbacker.usuario.is_caa: feedback_caa = feedback document = MailMerge(self.template) print(document.get_merge_fields()) document.merge(order=self.solicitation.order, date=str(self.solicitation.created_at.day) + "/" + str(self.solicitation.created_at.month) + "/" + str(self.solicitation.created_at.year), name=self.solicitation.student.usuario.name, code=self.solicitation.code, email=self.solicitation.email, course=("Tecnólogo em gestão pública"), phone1=self.solicitation.phone1, phone2=self.solicitation.phone2, semester=self.solicitation.student_semester, classs=self.solicitation.classs, student_academic_situation=self.solicitation. student_academic_situation, solicitation=self.solicitation.solicitation, reason=self.solicitation.reason, secretary_feedback=feedback_secretary.feedback, coord_feedback=feedback_coord.feedback, dir_feedback=feedback_dir.feedback, napes_feedback=feedback_napes.feedback, lib_feedback=feedback_lib.feedback, finance_feedback=feedback_fin.feedback, caa_feedback=feedback_caa.feedback) document.write( "secretariavirtual/common-static/static/solicitations/" + self.document_name)
for idbarang in daftar_barang: nama_barang = idbarang[0] nama_file = str(nama_barang); #nama_file = nama_file.replace("/", "") #nama_lokasi = db.escape_string(nama_lokasi) sql = ''' 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')
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 generate_doc(template, data, output): document = MailMerge((template)) document.merge(**data) print(document.get_merge_fields()) document.write(output)
def show(): read_excel() new_folder() a = [] for var in v: a.append(var.get()) #模板文档 template0_ELB = r".\tem\ELB_template.docx" template1_ELCK = r".\tem\ELCK_template.docx" template2_ELF = r".\tem\ELF_template.docx" template3_ELM = r".\tem\ELM_template.docx" template4_ELN = r".\tem\ELN_template.docx" template5_ELP = r".\tem\ELP_template.docx" template6_ELQC = r".\tem\ELQC_template.docx" template7_ELW = r".\tem\ELW_template.docx" template8_ELHC = r".\tem\ELHC_template.docx" template9_ELSMT = r".\tem\ELSMT_template.docx" template10_ELT = r".\tem\ELT_template.docx" template11_ELY = r".\tem\ELY_template.docx" template12_FIL_H = r".\tem\ELFIL_film_h.docx" template13_FIL_X = r".\tem\ELFIL_film_x.docx" template14_ELREF = r".\tem\ELREF_template.docx" template15_ELPCB = r".\tem\ELPCB_template.docx" #主判断 if a[0] == 1: #ELB document0 = MailMerge(template0_ELB) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'custom_code': str(cus_num), 'time': '{:%Y-%m-%d}'.format(date.today()), 'pack_name': str(in_pack), } document0.merge_pages([cust_1]) document0.write("./{}/ELB{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需增加版本信息版本 if a[1] == 1: #ELCK document1 = MailMerge(template1_ELCK) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'P_name': pcb_name, 'time': '{:%Y-%m-%d}'.format(date.today()), 'pack_name': str(in_pack), } document1.merge_pages([cust_1]) document1.write("./{}/ELB{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需修改 if a[2] == 1: #ELF document2 = MailMerge(template2_ELF) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'P_name': pcb_name, 'R_name': ref_name, 'time': '{:%Y-%m-%d}'.format(date.today()), } document2.merge_pages([cust_1]) document2.write("./{}/ELF{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需修改 if a[3] == 1: #ELM document3 = MailMerge(template3_ELM) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'F_name': film_name, 'time': '{:%Y-%m-%d}'.format(date.today()) } document3.merge_pages([cust_1]) document3.write("./{}/ELM{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需修改 if a[4] == 1: #ELN document4 = MailMerge(template4_ELN) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'P_name': pcb_name, 'time': '{:%Y-%m-%d}'.format(date.today()) } document4.merge_pages([cust_1]) document4.write("./{}/ELN{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需修改 if a[5] == 1: #ELP document5 = MailMerge(template5_ELP) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'P_name': pcb_name, 'time': '{:%Y-%m-%d}'.format(date.today()) } document5.merge_pages([cust_1]) document5.write("./{}/ELP{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) if a[6] == 1: #ELQC document6 = MailMerge(template6_ELQC) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'time': '{:%Y-%m-%d}'.format(date.today()) } document6.merge_pages([cust_1]) document6.write("./{}/ELQC{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需修改 if a[7] == 1: #ELW document7 = MailMerge(template7_ELW) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'custom_code': str(cus_num), 'pcb_name': pcb_name, 'pcb_sup': pcb_sup, 'pin_head': pin_head, 'pin_name': pin_name, 'ref_name': ref_name, 'ref_texture': ref_texture, 'ref_ink': ref_ink, 'ref_sup': ref_sup, 'film_name': film_name, 'film_sup': film_sup, 'easy_tape': easy_tape, 'easy_sup': easy_sup, 'in_pack': in_pack, 'out_pack': out_pack, 'time': '{:%Y-%m-%d}'.format(date.today()) } document7.merge_pages([cust_1]) document7.write("./{}/ELW{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需修改 if a[8] == 1: #ELHC document8 = MailMerge(template8_ELHC) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'custom_code': str(cus_num), 'time': '{:%Y-%m-%d}'.format(date.today()) } document8.merge_pages([cust_1]) document8.write("./{}/ELHC{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) #需修改 if a[9] == 1: #ELSMT document9 = MailMerge(template9_ELSMT) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'P_name': pcb_name, 'pcb_sup': pcb_sup, 'time': '{:%Y-%m-%d}'.format(date.today()) } document9.merge_pages([cust_1]) document9.write("./{}/ELSMT{}-{}SMT加工技术文件.docx".format( new_folder_name, tjp_num, Pro_name)) #需修改 if a[10] == 1: #ELT document10 = MailMerge(template10_ELT) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'custom_code': str(cus_num), 'time': '{:%Y-%m-%d}'.format(date.today()) } document10.merge_pages([cust_1]) document10.write("./{}/ELT{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) if a[11] == 1: #ELY document11 = MailMerge(template11_ELY) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'P_name': pcb_name, 'ref_name': ref_name, 'time': '{:%Y-%m-%d}'.format(date.today()) } document11.merge_pages([cust_1]) document11.write("./{}/ELY{}-{}.docx".format(new_folder_name, tjp_num, Pro_name)) if a[12] == 1: #ELFIL_H 缺少film_texture document12 = MailMerge(template12_FIL_H) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'supper': film_sup, # 'texture':, 'time': '{:%Y-%m-%d}'.format(date.today()) } document12.merge_pages([cust_1]) document12.write("./{}/ELFIL{}面膜核准单({} {}).docx".format( new_folder_name, tjp_num, film_sup, Pro_name)) if a[13] == 1: #ELFIL_X document13 = MailMerge(template13_FIL_X) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'supper': film_sup, 'time': '{:%Y-%m-%d}'.format(date.today()) } document13.merge_pages([cust_1]) document13.write("./{}/ELFIL{}面膜限度样品({} {}).docx".format( new_folder_name, tjp_num, film_sup, Pro_name)) if a[14] == 1: #ELREF document14 = MailMerge(template14_ELREF) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'ref_name': ref_name, 'ref_texture': ref_texture, 'ref_sup': ref_sup, 'ref_ink': ref_ink, 'time': '{:%Y-%m-%d}'.format(date.today()), } document14.merge_pages([cust_1]) document14.write("./{}/ELREF{}塑壳材料核准单({}-{}).docx".format( new_folder_name, tjp_num, ref_sup, ref_name)) if a[15] == 1: #ELPCB document15 = MailMerge(template15_ELPCB) cust_1 = { 'name': Pro_name, 'bianhao': str(tjp_num), 'time': '{:%Y-%m-%d}'.format(date.today()), 'P_name': pcb_name, 'pcb_sup': pcb_sup } document15.merge_pages([cust_1]) document15.write("./{}/ELPCB{}线路板材料核准单({}-{}).docx".format( new_folder_name, tjp_num, pcb_sup, pcb_name)) # if a[16] ==1: #ELPF # document1 =MailMerge(template0_ELB) # cust_1 = {'name': '1', #需修改读入 # 'time': '{:%B %d,%Y}'.format(date.today()), # 'pack_name': '{:%Y-%m-%d}'.format(date.today()), # 'bianhao': '12342', # 'custom_code': '123' # } # document1.merge_pages([cust_1]) # document1.write("./{}.docx".format(12)) #需修改 message()
class handle_merge(): def __init__(self): self.df_data = pd.DataFrame() self.template = 'C:/temp/mm/Test.docx' self.datafile = 'C:/temp/mm/Test.xlsx' self.path = 'C:/temp/mm/' self.document_1 = MailMerge(self.template) def read_files(self, ): # df_data = pd.DataFrame() try: self.df_data = pd.DataFrame( pd.read_excel( io=self.datafile, sheet_name='Sheet1', # dtype={'ZF Global ID': 'str'}, header=0, # skiprows=2)) )) print(self.df_data.head()) except Exception as e: print('Handle Employee Data Exception:', self.datafile, e) # def generate_pdf(self,docfile, pdf_file): # # wdFormatPDF = 17 # word = DispatchEx("Word.Application") # try: # doc = word.Documents.Open(docfile, ReadOnly=1) # # doc.SaveAs(pdf_file, FileFormat=wdFormatPDF) # doc.ExportAsFixedFormat(OutputFileName=pdf_file, # ExportFormat=17, # 17 = PDF output, 18=XPS output # OpenAfterExport=False, # OptimizeFor=0, # 0=Print (higher res), 1=Screen (lower res) # CreateBookmarks=1, # # 0=No bookmarks, 1=Heading bookmarks only, 2=bookmarks match word bookmarks # DocStructureTags=True # ); # doc.Close() # except Exception as e: # print('convert pdf failed,', docfile) def main(self): print(self.document_1.get_merge_fields()) self.read_files() for n_idx, n_row in self.df_data.iterrows(): dict = { "姓名": str(n_row['姓名']), "年龄": str(n_row['年龄']), "生日": str(n_row['生日']), "folder": 'folder1' } self.document_1.merge(**dict) file_path = self.path + 'xlsx/' if not os.path.exists(file_path): os.makedirs(file_path) file_docx = self.path + 'xlsx/' + n_row['姓名'] + '.docx' self.document_1.write(file_docx) # time.sleep(1) file_path = self.path + n_row['性别'] + '/' if not os.path.exists(file_path): os.makedirs(file_path) file_pdf = file_path + n_row['姓名'] + '.pdf' # file_pdf = self.path + 'pdfs/' + n_row['姓名'] + '.pdf' # self.generate_pdf(file_docx,file_pdf) convert(file_docx, file_pdf, keep_active=True) self.document_1.close()
def template(): for i in range(8, max_row + 1): c_temp = sheet.cell(i, 1) ##Filter to pick out templates if c_temp.value == "CNR": document = MailMerge(template_1) ## Ideally, i can set up the transfer between Word and Excel #This can be solved by creating an index from variable names and itterate. Also, possibly and iloc solution instead of sheet cell plugs name = sheet.cell(2, 2) matter = sheet.cell(3, 2) dob = sheet.cell(4, 2) # Might find a "matching value" search to automate assignment from excel cell variables to merge fields ## After preseting mail merge fields, this operation needs to be automated, hopefully by itteration. document.merge(Name=name.value) document.merge(Matter=str(matter.value)) # need to add date formating document.merge(DOB=str(dob.value)) for j in range(1, max_column + 1): cel_obj = sheet.cell(row=i, column=j) if j == 2: document.merge(Addressee=cel_obj.value) addressee = cel_obj.value if j == 3: # need to add date formating document.merge(From=str(cel_obj.value)) if j == 4: # need to add date formating document.merge(to=str(cel_obj.value)) document.write(r"C:\Users\anton\OneDrive\Desktop\CNRtemp" + addressee + ".docx") elif c_temp.value == "AB": document = MailMerge(template_2) name = sheet.cell(2, 2) matter = sheet.cell(3, 2) dob = sheet.cell(4, 2) document.merge(Name=name.value) document.merge(Matter=str(matter.value)) # need to add date formating document.merge(DOB=str(dob.value)) for j in range(1, max_column + 1): cel_obj = sheet.cell(row=i, column=j) if j == 2: document.merge(Addressee=cel_obj.value) addressee = cel_obj.value if j == 3: # need to add date formating document.merge(From=str(cel_obj.value)) if j == 4: # need to add date formating document.merge(to=str(cel_obj.value)) document.write(r"C:\Users\anton\OneDrive\Desktop\AB" + addressee + ".docx") else: continue
def __init__(self): self.df_data = pd.DataFrame() self.template = 'C:/temp/mm/Test.docx' self.datafile = 'C:/temp/mm/Test.xlsx' self.path = 'C:/temp/mm/' self.document_1 = MailMerge(self.template)
server = '{}'.format(var[1]) port = '{}'.format(var[2]) db ='{}'.format(var[3]) user = '******'.format(var[4]) pw = '{}'.format(var[5]) conn_str = ';'.join([driver, server, port, db, user, pw]) connetion = pyodbc.connect(conn_str) coursor = connetion.cousor() result = coursor.execute("SELECT pfio, akt_number, dbeg_akt, dend_akt, pricepol FROM OPERS_AKTS WHERE dog_date LIKE %2019% ORDER by akt_number").fetchall() user = coursor.execute("SELECT pfio, name_work, dog_n, date_beg,date_end FROM OPERS WHERE date_beg LIKE %2019% ORDER by pfio").fetchall() # Заполняем акты df = df -2 for i in range (df): template = r"Акт сдачи-приеки.docx" document = MailMerge(template) signal = 0 if "ИП " in oper[i]: signal = 1 oper[i] = per[i][3:] pfio, name_work, dog_n, date_beg,date_end = search(oper[i]) n_act, startD, endD, cost = searchact(oper[i]) if signal == 1: name_work = "ИП " +name_work signal = 0 date_act = dt operator = name_work print(operator) period = startD.strftime("%d.%m.%Y") +' - '+ endD.strftime("%d.%m.%Y") pwd = passwd[i] n_vs = n_ep = ""
def test(self): MailMerge("tests/test_issue2.docx")
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)
def setUp(self): self.document = MailMerge(path.join(path.dirname(__file__), 'test_merge_table_rows.docx')) self.expected_tree = etree.fromstring('<w:document xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ns1="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" mc:Ignorable="w14 wp14"><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
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')
def test(self): document = MailMerge(path.join(path.dirname(__file__), 'test_issue8.docx')) self.assertEqual(document.get_merge_fields(), {'testfield'})
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)
outputPath = sys.argv[5] spreadsheet = sys.argv[1] template = sys.argv[2] sheetname = sys.argv[3] rangee = sys.argv[4] print(sys.argv) # Handling if all rows in spreadsheet or just a defined amount if rangee != 'all': rangestart = rangee.split('-')[0] rangeend = rangee.split('-')[1] rangee = 'defined' else: rangee = rangee document = MailMerge(template) # Initializes Excel source file and sheet name variables provided by user wb = xlrd.open_workbook(spreadsheet) # Name of your excel file sheet = wb.sheet_by_name(sheetname) # Name of the sheet within your workbook # Defining loop range if rangee == 'all': firstRow = 1 lastRow = sheet.nrows if rangee == 'defined': firstRow = int(rangestart) lastRow = int(rangeend) + 1 #create output path if doesnt exist if not os.path.exists(outputPath):
def all(): sg.theme('DarkBlue12') #sg.theme('Green') #sg.theme_previewer() layout2 = [[ sg.Text('Укажите расположение до Word-шаблона:', size=(35, 1)), sg.InputText(size=(80, 1)), sg.FileBrowse() ], [ sg.Text('Укажите расположение файла Excel:', size=(35, 1)), sg.InputText(size=(80, 1)), sg.FileBrowse() ], [ sg.Text('Укажите путь для сохранения Паспортов:', size=(35, 1)), sg.InputText(size=(80, 1)), sg.FolderBrowse() ], [sg.Submit(), sg.Cancel()]] window2 = sg.Window('Меню', layout2) event, values = window2.read() window2.close() WORD_path, Excel_path, Save_path = values[0], values[1], values[2] wb = load_workbook(Excel_path) sheet = wb.worksheets[0] for cell in sheet["A"]: if cell.value is None: cl = cell.row #print(cl) break short_asu = [] for val in range(4, cl): short_asu.append(sheet.cell(row=val, column=4).value) sg.theme('DarkBlue12') progressbar = [[ sg.ProgressBar(len(short_asu), orientation='h', size=(51, 10), key='progressbar') ]] outputwin = [[sg.Output(size=(78, 20))]] layout = [[sg.Frame('Progress', layout=progressbar)], [sg.Frame('Output', layout=outputwin)], [sg.Submit('Start'), sg.Cancel()]] window = sg.Window('Custom Progress Meter', layout) progress_bar = window['progressbar'] while True: event, values = window.read(timeout=10) if event == 'Cancel' or event is None: break raise SystemExit(1) elif event == 'Start': print("****** START ******") try: files = os.listdir(Save_path) if not files: os.mkdir(Save_path + '/' + 'Шаблоны_паспортов') info_dir = 0 for f, n in enumerate(files): if n == 'Шаблоны_паспортов': info_dir = 1 else: info_dir = 2 if info_dir == 2: os.mkdir(Save_path + '/' + 'Шаблоны_паспортов') for d, item in enumerate(short_asu, 4): myASU = [] for val in range(1, 49): myASU.append(sheet.cell(row=d, column=val).value) document = MailMerge(WORD_path) # print(document.get_merge_fields()) # print(myASU) document.merge( Полное_наим=str(myASU[1]), Краткое_наим=str(myASU[2]), Краткое_наим_2=str(myASU[3]), Собственник_АСУ_ТП=str(myASU[4]), Эксп_Орг=str(myASU[5]), Назначение_п1_3=str(myASU[6]), Владелец_АСУТП=str(myASU[7]), п1_6=str(myASU[8]), Класс_Опасности=str(myASU[9]), Крит_Тех_Проц=str(myASU[10]), Соц_знач=str(myASU[11]), Эконом_знач=str(myASU[12]), Эколог_знач=str(myASU[13]), п1_10=str(myASU[14]), Режим_работы_АСУ_ТП=str(myASU[15]), Наим_Тех_проц=str(myASU[16]), Описание_п3_1=str(myASU[17]), Описание_п3_2=str(myASU[18]), Описание_п3_3=str(myASU[19]), п3_7=str(myASU[20]), Идент_Аутент=str(myASU[21]), Описание_табл_п5_1=str(myASU[22]), Упр_Доступом=str(myASU[23]), Огрн_прог_среды=str(myASU[24]), Защита_маш_нос_инф=str(myASU[25]), Ауд_ИБ=str(myASU[26]), Антивир=str(myASU[27]), Пред_Вторж=str(myASU[28]), Целостность=str(myASU[29]), Резерв_оборуд=str(myASU[30]), Рез_Коп=str(myASU[31]), ЗИП=str(myASU[32]), Мон_Тех_Сост=str(myASU[33]), п5_10=str(myASU[34]), Меры_физ_защ1=str(myASU[35]), Меры_физ_защ2=str(myASU[36]), Меры_физ_защ3=str(myASU[37]), Меры_физ_защ4=str(myASU[38]), Меры_физ_защ5=str(myASU[39]), ИБП=str(myASU[40]), п5_11=str(myASU[41]), п5_12=str(myASU[42]), У_Конфиг=str(myASU[43]), п5_14=str(myASU[44]), Реаг_Инц_ИБ=str(myASU[45]), п6_16=str(myASU[46]), Инф_обуч_персн=str(myASU[47]), ) document.write(Save_path + '/' + str(myASU[0]) + '_' + 'Паспорт_' + myASU[3] + '.docx') dubl = Document(WORD_path) fulPath = Save_path + '/' + 'Шаблоны_паспортов/' + 'Шаблон_' + str( myASU[0]) + '_' + myASU[3] + '.docx' dubl.save(fulPath) print(str(myASU[0]) + ") ", myASU[3], " - Done") progress_bar.UpdateBar(d + 1) print("****** FINISH ******") except: print("***** SHIT,ERROR ******") window.close()
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
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())
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case, # the inbox. messages = inbox.Items.Restrict("[ReceivedTime] >= '" + str(datetime.date.today()) + "'") for message in reversed(messages): if loop_run: break subject = message.subject Ex_extract = False if re.search("Mail Subject", str(subject)) : body = message.Body body_list = body.splitlines() for val in body_list: if Ex_extract: Ex_list.append(val) if re.search("Example :", val): Ex_extract = True loop_run = True template = 'ABC_Template.docx' document = MailMerge(template) print(document.get_merge_fields()) document.merge( Example = ', '.join(Ex_list) ) document.write('ABC.docx') document.close()
# @File :excelToWord.py # 导入xlrd模块 导入mailerge模块 读取excel 以及写入word import xlrd from xlutils.copy import copy from mailmerge import MailMerge #设置文件名和路径 fname = 'd:/excelToWord/dms数据字典.xlsx' #打开文件 filename = xlrd.open_workbook(fname) # 获取当前文档的表(得到的是sheet的个数,一个整数) sheets = filename.nsheets sheet = filename.sheets()[0] #通过sheet索引获得sheet对象 # print sheet #获取行数 nrows = sheet.nrows # 获取列数 ncols = sheet.ncols #获取第一行,第一列数据数据 cell_value = sheet.cell_value(1, 1) print(cell_value) #打开模版 template = 'd:/excelToWord/模版.docx' document = MailMerge(template) print("Fields included in {}: {}".format(template, document.get_merge_fields())) document.merge(test=cell_value) document.write('d:/完成word.docx') print('数据写入成功!')
from __future__ import print_function from mailmerge import MailMerge from datetime import date # Define the templates - assumes they are in the same directory as the code template_1 = "Practical-Business-Python.docx" template_2 = "Practical-Business-Python-History.docx" # Show a simple example document_1 = MailMerge(template_1) print("Fields included in {}: {}".format(template_1, document_1.get_merge_fields())) # Merge in the values document_1.merge( status='Gold', city='Springfield', phone_number='800-555-5555', Business='Cool Shoes', zip='55555', purchases='$500,000', shipping_limit='$500', state='MO', address='1234 Main Street', date='{:%d-%b-%Y}'.format(date.today()), discount='5%', recipient='Mr. Jones') # Save the document as example 1 document_1.write('example1.docx')
class MergeTableRowsTest(EtreeMixin, unittest.TestCase): def setUp(self): self.document = MailMerge(path.join(path.dirname(__file__), 'test_merge_table_rows.docx')) self.expected_tree = etree.fromstring('<w:document xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:ns1="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" mc:Ignorable="w14 wp14"><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_rows_no_table(self): """ Merging of rows should not fail if there is no table with the given column in the document """ 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'}, ], no_table=[ {'no_table': 'Table not available'} ] ) 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_rows_remove_table(self): """ When flag is set and there is no data in a table, table needs to be removed """ self.document.remove_empty_tables = True self.document.merge( student_name='Bouke Haarsma', study='Industrial Engineering and Management', thesis_grade='A', class_code=[] ) with tempfile.TemporaryFile() as outfile: self.document.write(outfile) self.assertIsNone( list(self.document.parts.values())[0].getroot().find('.//{%(w)s}tbl' % NAMESPACES) ) 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())
from mailmerge import MailMerge import os from datetime import datetime as dt # MS Word 템플릿 파일 불러오기 cwd = os.getcwd() template_filename = "fax_cover_template.docx" template_filepath = os.path.join(cwd, "data", template_filename) # 템플릿 파일로 메일머지(mail-merge) 객체 만들기 document = MailMerge(template_filepath) # 수신자 정보 입력하고, 메일머지 객체에 전달하기 document.merge( name='박수민', fax='031-777-7777', phone='031-777-7700', date='%s년 %s월 %s일' % (dt.now().year, dt.now().month, dt.now().day), title='세금계산서 재발행 요청의 건', memo='2019년 8월분', ) # 메일머지 객체를 MS Word 문서로 저장하기 output_filepath = os.path.join(cwd, "output", "fax_cover_output.docx") document.write(output_filepath)