#以下開始產生WORD檔程序
#取df的資料筆數
row_cnt = df.shape[0]
#print(str(df.shape[0]))

#取df的資料欄位數
col_cnt = df.shape[1]
#print(str(df.shape[1]))

document = Document()

#文件格式風格設定
obj_styles = document.styles
obj_charstyle = obj_styles.add_style('CommentsStyle', WD_STYLE_TYPE.CHARACTER)
obj_font = obj_charstyle.font
obj_font.size = Pt(16)
#obj_font.name = 'Times New Roman'
obj_font.name = '標楷體'
obj_font.color.rgb = RGBColor(0x0, 0x0, 0xff)

#文件內文段落
paragraph = document.add_paragraph()
paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

#文件抬頭
run = paragraph.add_run(str(yyy) + '年度生產資訊處工作實績一覽表', style='CommentsStyle')

#加入表格
t = document.add_table(rows=row_cnt + 1, cols=col_cnt - 3, style='Light List')
#t.style = 'Table Grid'
#t.style = 'Medium Shading 2 Accent 1'
示例#2
0
    def _write_static_p2(self) -> None:
        """Write the second part of the report after test result table.
        """
        para = self.doc.add_paragraph()
        self.add_line_break(para, 2, Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("5   Verification Details")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.add_text("Below table details the summary of the completion of verification cycle. ")

        table = self.doc.add_table(rows=9, cols=2)
        for i in range(len(table.rows)):
            for j in range(len(table.columns)):
                run = table.rows[i].cells[j].paragraphs[0].add_run()

                if i == 0 or j == 0:
                    run.bold = True

        table.style = "Table Grid"
        self.fill_table(
            table,
            [["Activity", "Details"],
             [
                 "Test set location in ALM",
                 "URL: http://hc-alm12.health.ge.com/qcbin/start_a.jsp "
                 "Domain: SWPE / Project: HealthCloud \n ALM\Test Lab\<location of ALM test set>"
             ], ["Verification Cycle Start Date", ""], ["Verification Cycle End Date", ""],
             ["Name of the Tester(s)", ""], ["Total # of test cases executed", ""], ["Total # of Defects Filed", ""],
             ["Total # of Tests Passed", ""], ["Total # of Tests Failed", ""]])

        para = self.doc.add_paragraph()
        self.add_line_break(para, 2, Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("6   Defect Summary List")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.add_text("Below table summarizes the defects found during verification cycle."
                     "The defects are tracked in ALM: http://hc-alm12.health.ge.com/qcbin/start_a.jsp"
                     "Domain: SWPE / Project: HealthCloud")

        table = self.doc.add_table(rows=2, cols=5)
        for i in range(len(table.rows)):
            for j in range(len(table.columns)):
                run = table.rows[i].cells[j].paragraphs[0].add_run()
                if i == 0:
                    run.bold = True

        table.style = "Table Grid"
        self.fill_table(table,
                        [["Defect ID", "Summary", "Classification", "Status", "Justification"], ["", "", "", "", ""]])

        para = self.doc.add_paragraph()
        self.add_line_break(para, 2, Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("7   Verification Deviations")

        table = self.doc.add_table(rows=2, cols=1)
        for i in range(len(table.rows)):
            for j in range(len(table.columns)):
                run = table.rows[i].cells[j].paragraphs[0].add_run()

        table.style = "Table Grid"
        self.fill_table(table,
                        [["There were no deviations from the verification plan."],
                         ["There were deviations from the verification plan as follows"]])

        para = self.doc.add_paragraph()
        self.add_line_break(para, 2, Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("8   Conclusion")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.add_text("The acceptance criteria identified in the Verification plan have been met. All activities "
                     "supporting this verification activity are complete.")
示例#3
0
df = pd.read_excel(
    "/Users/wangsiren/Downloads/ForHBNUSU/LiteratureandSportsDept/人名学号对照表.xlsx",
    usecols=[0, 1, 2, 3],
    names=None)  # 读取项目名称列,不要列名
df_li = df.values.tolist()
result = []
for s_li in df_li:
    result.append(s_li)

document = Document(
    "/Users/wangsiren/Downloads/ForHBNUSU/LiteratureandSportsDept/空白A4.docx")
document.styles['Normal'].font.name = u'宋体'
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
style = document.styles['Normal']
font = style.font
font.size = Pt(14)

table0 = document.add_table(rows=1, cols=1)
cell0 = table0.cell(0, 0)
cell0.text = result[0][2] + "\n" + "带队老师:" + result[0][3]
cell0.paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
cell0.paragraphs[0].paragraph_format.alignment = WD_ALIGN_VERTICAL.CENTER
run = table0.cell(0, 0).paragraphs[0].add_run('smida')
run.font.name = '宋体'
run.font.size = 14

total = len(result)
print(len(result))
C = 3
R = total // C * 2
n = 0
示例#4
0
tables[0].cell(0, 0).paragraphs[0].text = 'АО "Стоун банк" Г. МОСКВА'
tables[0].cell(0, 3).paragraphs[0].text = '044525700'
tables[0].cell(1, 3).paragraphs[0].text = '30101810200000000700'
tables[0].cell(3, 0).paragraphs[0].text = 'ИНН 7722737766'
tables[0].cell(3, 1).paragraphs[0].text = 'КПП 772201001'
tables[0].cell(3, 3).paragraphs[0].text = '40702810900000002453'
tables[0].cell(4, 0).paragraphs[0].text = 'ООО "Василек"'

tables[1].cell(0, 0).text = 'Счет на оплату №11 от 13 мая 2020 г.'

run = tables[1].cell(0, 0).paragraphs[0]
run.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = run.runs[0]
run.font.bold = True
run.font.size=Pt(13)

t_i = 'ООО "ВАСИЛЕК", ИНН 7722737753, КПП 772201001, 109052, '
t_i += 'г. Москва ул. Добрынинская, д. 70, корпус 2, тел: 12345'
tables[2].cell(0, 1).text = t_i
run = tables[2].cell(0, 1).paragraphs[0].runs[0]
run.font.bold = True
t_z = 'ООО "ЛАГУНА", ИНН 7714737457, КПП 772864077, 106752, '
t_z += 'г. Москва ул. Тульская, д. 67, корпус 5, тел: 54321'
tables[2].cell(1, 1).text = t_z
run = tables[2].cell(1, 1).paragraphs[0].runs[0]
run.font.bold = True
tables[2].cell(2, 1).text = "№20022016 от 13.05.20"
run = tables[2].cell(2, 1).paragraphs[0].runs[0]
run.font.bold = True
示例#5
0
class DescribeFont(object):

    def it_provides_access_to_its_color_object(self, color_fixture):
        font, color_, ColorFormat_ = color_fixture
        color = font.color
        ColorFormat_.assert_called_once_with(font.element)
        assert color is color_

    def it_knows_its_typeface_name(self, name_get_fixture):
        font, expected_value = name_get_fixture
        assert font.name == expected_value

    def it_can_change_its_typeface_name(self, name_set_fixture):
        font, value, expected_xml = name_set_fixture
        font.name = value
        assert font._element.xml == expected_xml

    def it_knows_its_size(self, size_get_fixture):
        font, expected_value = size_get_fixture
        assert font.size == expected_value

    def it_can_change_its_size(self, size_set_fixture):
        font, value, expected_xml = size_set_fixture
        font.size = value
        assert font._element.xml == expected_xml

    def it_knows_its_bool_prop_states(self, bool_prop_get_fixture):
        font, prop_name, expected_state = bool_prop_get_fixture
        assert getattr(font, prop_name) == expected_state

    def it_can_change_its_bool_prop_settings(self, bool_prop_set_fixture):
        font, prop_name, value, expected_xml = bool_prop_set_fixture
        setattr(font, prop_name, value)
        assert font._element.xml == expected_xml

    def it_knows_whether_it_is_subscript(self, subscript_get_fixture):
        font, expected_value = subscript_get_fixture
        assert font.subscript == expected_value

    def it_can_change_whether_it_is_subscript(self, subscript_set_fixture):
        font, value, expected_xml = subscript_set_fixture
        font.subscript = value
        assert font._element.xml == expected_xml

    def it_knows_whether_it_is_superscript(self, superscript_get_fixture):
        font, expected_value = superscript_get_fixture
        assert font.superscript == expected_value

    def it_can_change_whether_it_is_superscript(self, superscript_set_fixture):
        font, value, expected_xml = superscript_set_fixture
        font.superscript = value
        assert font._element.xml == expected_xml

    def it_knows_its_underline_type(self, underline_get_fixture):
        font, expected_value = underline_get_fixture
        assert font.underline is expected_value

    def it_can_change_its_underline_type(self, underline_set_fixture):
        font, underline, expected_xml = underline_set_fixture
        font.underline = underline
        assert font._element.xml == expected_xml

    def it_knows_its_highlight_color(self, highlight_get_fixture):
        font, expected_value = highlight_get_fixture
        assert font.highlight_color is expected_value

    def it_can_change_its_highlight_color(self, highlight_set_fixture):
        font, highlight_color, expected_xml = highlight_set_fixture
        font.highlight_color = highlight_color
        assert font._element.xml == expected_xml

    # fixtures -------------------------------------------------------

    @pytest.fixture(params=[
        ('w:r/w:rPr',                          'all_caps',       None),
        ('w:r/w:rPr/w:caps',                   'all_caps',       True),
        ('w:r/w:rPr/w:caps{w:val=on}',         'all_caps',       True),
        ('w:r/w:rPr/w:caps{w:val=off}',        'all_caps',       False),
        ('w:r/w:rPr/w:b{w:val=1}',             'bold',           True),
        ('w:r/w:rPr/w:i{w:val=0}',             'italic',         False),
        ('w:r/w:rPr/w:cs{w:val=true}',         'complex_script', True),
        ('w:r/w:rPr/w:bCs{w:val=false}',       'cs_bold',        False),
        ('w:r/w:rPr/w:iCs{w:val=on}',          'cs_italic',      True),
        ('w:r/w:rPr/w:dstrike{w:val=off}',     'double_strike',  False),
        ('w:r/w:rPr/w:emboss{w:val=1}',        'emboss',         True),
        ('w:r/w:rPr/w:vanish{w:val=0}',        'hidden',         False),
        ('w:r/w:rPr/w:i{w:val=true}',          'italic',         True),
        ('w:r/w:rPr/w:imprint{w:val=false}',   'imprint',        False),
        ('w:r/w:rPr/w:oMath{w:val=on}',        'math',           True),
        ('w:r/w:rPr/w:noProof{w:val=off}',     'no_proof',       False),
        ('w:r/w:rPr/w:outline{w:val=1}',       'outline',        True),
        ('w:r/w:rPr/w:rtl{w:val=0}',           'rtl',            False),
        ('w:r/w:rPr/w:shadow{w:val=true}',     'shadow',         True),
        ('w:r/w:rPr/w:smallCaps{w:val=false}', 'small_caps',     False),
        ('w:r/w:rPr/w:snapToGrid{w:val=on}',   'snap_to_grid',   True),
        ('w:r/w:rPr/w:specVanish{w:val=off}',  'spec_vanish',    False),
        ('w:r/w:rPr/w:strike{w:val=1}',        'strike',         True),
        ('w:r/w:rPr/w:webHidden{w:val=0}',     'web_hidden',     False),
    ])
    def bool_prop_get_fixture(self, request):
        r_cxml, bool_prop_name, expected_value = request.param
        font = Font(element(r_cxml))
        return font, bool_prop_name, expected_value

    @pytest.fixture(params=[
        # nothing to True, False, and None ---------------------------
        ('w:r',                             'all_caps',       True,
         'w:r/w:rPr/w:caps'),
        ('w:r',                             'bold',           False,
         'w:r/w:rPr/w:b{w:val=0}'),
        ('w:r',                             'italic',         None,
         'w:r/w:rPr'),
        # default to True, False, and None ---------------------------
        ('w:r/w:rPr/w:cs',                  'complex_script', True,
         'w:r/w:rPr/w:cs'),
        ('w:r/w:rPr/w:bCs',                 'cs_bold',        False,
         'w:r/w:rPr/w:bCs{w:val=0}'),
        ('w:r/w:rPr/w:iCs',                 'cs_italic',      None,
         'w:r/w:rPr'),
        # True to True, False, and None ------------------------------
        ('w:r/w:rPr/w:dstrike{w:val=1}',    'double_strike',  True,
         'w:r/w:rPr/w:dstrike'),
        ('w:r/w:rPr/w:emboss{w:val=on}',    'emboss',         False,
         'w:r/w:rPr/w:emboss{w:val=0}'),
        ('w:r/w:rPr/w:vanish{w:val=1}',     'hidden',         None,
         'w:r/w:rPr'),
        # False to True, False, and None -----------------------------
        ('w:r/w:rPr/w:i{w:val=false}',      'italic',         True,
         'w:r/w:rPr/w:i'),
        ('w:r/w:rPr/w:imprint{w:val=0}',    'imprint',        False,
         'w:r/w:rPr/w:imprint{w:val=0}'),
        ('w:r/w:rPr/w:oMath{w:val=off}',    'math',           None,
         'w:r/w:rPr'),
        # random mix -------------------------------------------------
        ('w:r/w:rPr/w:noProof{w:val=1}',    'no_proof',       False,
         'w:r/w:rPr/w:noProof{w:val=0}'),
        ('w:r/w:rPr',                       'outline',        True,
         'w:r/w:rPr/w:outline'),
        ('w:r/w:rPr/w:rtl{w:val=true}',     'rtl',            False,
         'w:r/w:rPr/w:rtl{w:val=0}'),
        ('w:r/w:rPr/w:shadow{w:val=on}',    'shadow',         True,
         'w:r/w:rPr/w:shadow'),
        ('w:r/w:rPr/w:smallCaps',           'small_caps',     False,
         'w:r/w:rPr/w:smallCaps{w:val=0}'),
        ('w:r/w:rPr/w:snapToGrid',          'snap_to_grid',   True,
         'w:r/w:rPr/w:snapToGrid'),
        ('w:r/w:rPr/w:specVanish',          'spec_vanish',    None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:strike{w:val=foo}',   'strike',         True,
         'w:r/w:rPr/w:strike'),
        ('w:r/w:rPr/w:webHidden',           'web_hidden',     False,
         'w:r/w:rPr/w:webHidden{w:val=0}'),
    ])
    def bool_prop_set_fixture(self, request):
        r_cxml, prop_name, value, expected_cxml = request.param
        font = Font(element(r_cxml))
        expected_xml = xml(expected_cxml)
        return font, prop_name, value, expected_xml

    @pytest.fixture
    def color_fixture(self, ColorFormat_, color_):
        font = Font(element('w:r'))
        return font, color_, ColorFormat_

    @pytest.fixture(params=[
        ('w:r',                                  None),
        ('w:r/w:rPr',                            None),
        ('w:r/w:rPr/w:highlight{w:val=default}', WD_COLOR.AUTO),
        ('w:r/w:rPr/w:highlight{w:val=blue}',    WD_COLOR.BLUE),
    ])
    def highlight_get_fixture(self, request):
        r_cxml, expected_value = request.param
        font = Font(element(r_cxml), None)
        return font, expected_value

    @pytest.fixture(params=[
        ('w:r',                                 WD_COLOR.AUTO,
         'w:r/w:rPr/w:highlight{w:val=default}'),
        ('w:r/w:rPr',                           WD_COLOR.BRIGHT_GREEN,
         'w:r/w:rPr/w:highlight{w:val=green}'),
        ('w:r/w:rPr/w:highlight{w:val=green}',  WD_COLOR.YELLOW,
         'w:r/w:rPr/w:highlight{w:val=yellow}'),
        ('w:r/w:rPr/w:highlight{w:val=yellow}', None,
         'w:r/w:rPr'),
        ('w:r/w:rPr',                           None,
         'w:r/w:rPr'),
        ('w:r',                                 None,
         'w:r/w:rPr'),
    ])
    def highlight_set_fixture(self, request):
        r_cxml, value, expected_cxml = request.param
        font = Font(element(r_cxml), None)
        expected_xml = xml(expected_cxml)
        return font, value, expected_xml

    @pytest.fixture(params=[
        ('w:r',                               None),
        ('w:r/w:rPr',                         None),
        ('w:r/w:rPr/w:rFonts',                None),
        ('w:r/w:rPr/w:rFonts{w:ascii=Arial}', 'Arial'),
    ])
    def name_get_fixture(self, request):
        r_cxml, expected_value = request.param
        font = Font(element(r_cxml))
        return font, expected_value

    @pytest.fixture(params=[
        ('w:r',                                          'Foo',
         'w:r/w:rPr/w:rFonts{w:ascii=Foo,w:hAnsi=Foo,w:eastAsia=Foo}'),
        ('w:r/w:rPr',                                    'Foo',
         'w:r/w:rPr/w:rFonts{w:ascii=Foo,w:hAnsi=Foo,w:eastAsia=Foo}'),
        ('w:r/w:rPr/w:rFonts{w:hAnsi=Foo}',              'Bar',
         'w:r/w:rPr/w:rFonts{w:ascii=Bar,w:hAnsi=Bar,w:eastAsia=Bar}'),
        ('w:r/w:rPr/w:rFonts{w:ascii=Foo,w:hAnsi=Foo}',  'Bar',
         'w:r/w:rPr/w:rFonts{w:ascii=Bar,w:hAnsi=Bar,w:eastAsia=Bar}'),
    ])
    def name_set_fixture(self, request):
        r_cxml, value, expected_r_cxml = request.param
        font = Font(element(r_cxml))
        expected_xml = xml(expected_r_cxml)
        return font, value, expected_xml

    @pytest.fixture(params=[
        ('w:r',                      None),
        ('w:r/w:rPr',                None),
        ('w:r/w:rPr/w:sz{w:val=28}', Pt(14)),
    ])
    def size_get_fixture(self, request):
        r_cxml, expected_value = request.param
        font = Font(element(r_cxml))
        return font, expected_value

    @pytest.fixture(params=[
        ('w:r',                      Pt(12), 'w:r/w:rPr/w:sz{w:val=24}'),
        ('w:r/w:rPr',                Pt(12), 'w:r/w:rPr/w:sz{w:val=24}'),
        ('w:r/w:rPr/w:sz{w:val=24}', Pt(18), 'w:r/w:rPr/w:sz{w:val=36}'),
        ('w:r/w:rPr/w:sz{w:val=36}', None,   'w:r/w:rPr'),
    ])
    def size_set_fixture(self, request):
        r_cxml, value, expected_r_cxml = request.param
        font = Font(element(r_cxml))
        expected_xml = xml(expected_r_cxml)
        return font, value, expected_xml

    @pytest.fixture(params=[
        ('w:r',                                      None),
        ('w:r/w:rPr',                                None),
        ('w:r/w:rPr/w:vertAlign{w:val=baseline}',    False),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',   True),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}', False),
    ])
    def subscript_get_fixture(self, request):
        r_cxml, expected_value = request.param
        font = Font(element(r_cxml))
        return font, expected_value

    @pytest.fixture(params=[
        ('w:r',                                      True,
         'w:r/w:rPr/w:vertAlign{w:val=subscript}'),
        ('w:r',                                      False,
         'w:r/w:rPr'),
        ('w:r',                                      None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',   True,
         'w:r/w:rPr/w:vertAlign{w:val=subscript}'),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',   False,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',   None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}', True,
         'w:r/w:rPr/w:vertAlign{w:val=subscript}'),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}', False,
         'w:r/w:rPr/w:vertAlign{w:val=superscript}'),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}', None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=baseline}',    True,
         'w:r/w:rPr/w:vertAlign{w:val=subscript}'),
    ])
    def subscript_set_fixture(self, request):
        r_cxml, value, expected_r_cxml = request.param
        font = Font(element(r_cxml))
        expected_xml = xml(expected_r_cxml)
        return font, value, expected_xml

    @pytest.fixture(params=[
        ('w:r',                                      None),
        ('w:r/w:rPr',                                None),
        ('w:r/w:rPr/w:vertAlign{w:val=baseline}',    False),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',   False),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}', True),
    ])
    def superscript_get_fixture(self, request):
        r_cxml, expected_value = request.param
        font = Font(element(r_cxml))
        return font, expected_value

    @pytest.fixture(params=[
        ('w:r',                                       True,
         'w:r/w:rPr/w:vertAlign{w:val=superscript}'),
        ('w:r',                                       False,
         'w:r/w:rPr'),
        ('w:r',                                       None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}',  True,
         'w:r/w:rPr/w:vertAlign{w:val=superscript}'),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}',  False,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=superscript}',  None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',    True,
         'w:r/w:rPr/w:vertAlign{w:val=superscript}'),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',    False,
         'w:r/w:rPr/w:vertAlign{w:val=subscript}'),
        ('w:r/w:rPr/w:vertAlign{w:val=subscript}',    None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:vertAlign{w:val=baseline}',     True,
         'w:r/w:rPr/w:vertAlign{w:val=superscript}'),
    ])
    def superscript_set_fixture(self, request):
        r_cxml, value, expected_r_cxml = request.param
        font = Font(element(r_cxml))
        expected_xml = xml(expected_r_cxml)
        return font, value, expected_xml

    @pytest.fixture(params=[
        ('w:r',                         None),
        ('w:r/w:rPr/w:u',               None),
        ('w:r/w:rPr/w:u{w:val=single}', True),
        ('w:r/w:rPr/w:u{w:val=none}',   False),
        ('w:r/w:rPr/w:u{w:val=double}', WD_UNDERLINE.DOUBLE),
        ('w:r/w:rPr/w:u{w:val=wave}',   WD_UNDERLINE.WAVY),
    ])
    def underline_get_fixture(self, request):
        r_cxml, expected_value = request.param
        run = Font(element(r_cxml), None)
        return run, expected_value

    @pytest.fixture(params=[
        ('w:r', True,                'w:r/w:rPr/w:u{w:val=single}'),
        ('w:r', False,               'w:r/w:rPr/w:u{w:val=none}'),
        ('w:r', None,                'w:r/w:rPr'),
        ('w:r', WD_UNDERLINE.SINGLE, 'w:r/w:rPr/w:u{w:val=single}'),
        ('w:r', WD_UNDERLINE.THICK,  'w:r/w:rPr/w:u{w:val=thick}'),
        ('w:r/w:rPr/w:u{w:val=single}', True,
         'w:r/w:rPr/w:u{w:val=single}'),
        ('w:r/w:rPr/w:u{w:val=single}', False,
         'w:r/w:rPr/w:u{w:val=none}'),
        ('w:r/w:rPr/w:u{w:val=single}', None,
         'w:r/w:rPr'),
        ('w:r/w:rPr/w:u{w:val=single}', WD_UNDERLINE.SINGLE,
         'w:r/w:rPr/w:u{w:val=single}'),
        ('w:r/w:rPr/w:u{w:val=single}', WD_UNDERLINE.DOTTED,
         'w:r/w:rPr/w:u{w:val=dotted}'),
    ])
    def underline_set_fixture(self, request):
        initial_r_cxml, value, expected_cxml = request.param
        run = Font(element(initial_r_cxml), None)
        expected_xml = xml(expected_cxml)
        return run, value, expected_xml

    # fixture components ---------------------------------------------

    @pytest.fixture
    def color_(self, request):
        return instance_mock(request, ColorFormat)

    @pytest.fixture
    def ColorFormat_(self, request, color_):
        return class_mock(
            request, 'docx.text.font.ColorFormat', return_value=color_
        )
示例#6
0
    def SaveParagraph(self):
        # 设置doc文件相关参数
        titleStyle = {  # 标题字体参数
            'FontName': '方正小标宋_GBK',  # 名称
            'FontColor': RGBColor(0, 0, 0),  # 颜色
            'FontSize': 22,  # 字号, 二号=22, 小二=18, 三号=16, 小三=15, 四号=14, 小四=12
            'FontBold': False,  # 粗体
            'FontItalic': False,  # 斜体
            'FontUnderline': False  # 下划线
        }
        textStyle = {  # 正文字体参数
            'FontName': '方正仿宋_GBK',  # 字体
            'FontColor': RGBColor(0, 0, 0),  # 颜色
            'FontSize': 16,  # 字号, 二号=22, 小二=18, 三号=16, 小三=15, 四号=14, 小四=12
            'FontBold': False,  # 粗体
            'FontItalic': False,  # 斜体
            'FontUnderline': False  # 下划线
        }

        # 打开输出文件
        if not self.content[0]:
            print('Content[0] is empty!')
            sys.exit()
        outputPath = self.outputDir + str(self.content[0]) + '.docx'
        if os.path.exists(outputPath):
            rsfile = Document(outputPath)
        else:
            rsfile = Document()

        # 设置页面格式
        section = rsfile.sections[0]
        section.orientation = WD_ORIENT.PORTRAIT  # 页面方向
        section.top_margin = Cm(3.7)  # 页边距
        section.bottom_margin = Cm(3.5)
        section.left_margin = Cm(2.8)
        section.right_margin = Cm(2.6)

        # 正文文本输出
        # 排版需要,先在标题前后各增加一个空行
        self.content.insert(0, '')
        self.content.insert(2, '')
        for ip in range(len(self.content)):
            p = rsfile.add_paragraph()
            p.paragraph_format.left_indent = 0  # 左侧缩进
            p.paragraph_format.right_indent = 0  # 右侧缩进
            p.paragraph_format.space_before = 0  # 段前间距
            p.paragraph_format.space_after = 0  # 段后间距
            p.paragraph_format.line_spacing = Pt(28)  # 行间距

            run = p.add_run(self.content[ip])
            if ip <= 2:  # 标题
                p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
                self.AppFontStyle(run, titleStyle)
            else:  # 正文
                p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                p.paragraph_format.first_line_indent = Pt(
                    textStyle['FontSize'] * 2)  # 首行缩进
                self.AppFontStyle(run, textStyle)

        rsfile.save(outputPath)


#if __name__ == "__main__":
#    content = ['关于恳请协调在北沿江高铁如皋境内增设站点的情况汇报', '尊敬的李主席:', '首先,感谢您一直以来对如皋经济社会发展的关心和支持!今天来信,专程恳请您在百忙之中关心协调在北沿江高铁如皋境内增设站点事宜。']
#    outputDir = 'F:\\code-test\\python\\SaveToWord\\'
#    SaveToWord(content, outputDir).SaveParagraph()
示例#7
0
def login():
    sujet = request.form['sujet']
    type = request.form['type']
    serv = request.form['serv']
    numero = request.form['numero']
    source = request.form['source']
    client = request.form['client']
    description = request.form['description']

    doc = Document()
    section = doc.sections[0]
    header = section.header
    paragraph = header.paragraphs[0]
    paragraph.text = "\tCyber Security Innovation – Response Team"
    font = paragraph.style.font
    font.name = 'Hanzel Extended'
    font.size = Pt(14)
    font.color.rgb = RGBColor(19, 32, 223)

    parag = doc.add_paragraph()

    titre1 = parag.add_run('\t \t \tSecurity Bulletin N°' + client + ' ')
    font = titre1.font
    font.name = 'Cambria (Headings)'
    font.size = Pt(14)

    titre2 = parag.add_run(type)
    font = titre2.font
    font.name = 'Cambria (Headings)'
    font.size = Pt(14)

    font.bold = True

    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 128, 0)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    titre3 = parag.add_run('-')
    font = titre3.font
    font.name = 'Cambria (Headings)'
    font.size = Pt(14)

    font.bold = True

    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 51, 102)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    titre4 = parag.add_run(date + '-' + numero + '\n')
    font = titre4.font
    font.name = 'Cambria (Headings)'
    font.size = Pt(14)
    font.color.rgb = RGBColor(255, 128, 0)
    font.bold = True

    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 128, 0)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    parag.add_run('\n')

    titre5 = parag.add_run('Sujet: ' + sujet + '\n')
    if " " in sujet:
        sujet = sujet.replace(" ", "_")
    font = titre5.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True
    font.color.rgb = RGBColor(255, 255, 255)
    if (serv == "Elévé"):
        font.highlight_color = WD_COLOR_INDEX.RED
    elif (serv == "Moyenne"):
        font.highlight_color = WD_COLOR_INDEX.YELLOW
    else:
        font.highlight_color = WD_COLOR_INDEX.GREEN

    titre6 = parag.add_run("Référence:")
    font = titre6.font
    font.name = 'Cambria (Headings)'
    font.size = Pt(14)
    font.bold = True

    titre7 = parag.add_run(type + '-' + date + '-' + numero + '\n')
    font = titre7.font
    font.name = 'Calibri (Body)'
    font.size = Pt(16)

    font.bold = True
    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 128, 0)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    titre8 = parag.add_run("Sévérité: ")
    font = titre8.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    titre9 = parag.add_run(serv + '\n')
    font = titre9.font
    font.name = 'Liberation Serif'
    font.size = Pt(16)

    font.bold = True
    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 128, 0)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    titre10 = parag.add_run('Description: \n')
    font = titre10.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    titre11 = parag.add_run(description + '\n')
    font = titre11.font
    font.name = 'Calibri (Body)'
    font.size = Pt(12)

    titre12 = parag.add_run('Source: \n')
    font = titre12.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    p = doc.add_paragraph('')
    add_hyperlink(p, source, source)

    doc.save("Bulletin_" + client + "-" + type + "_" + date + "_" + "0" +
             numero + "_" + sujet + ".docx")

    os.system("start Bulletin_" + client + "-" + type + "_" + date + "_" +
              "0" + numero + "_" + sujet + ".docx")
    return render_template('index.html')
            subList.append(app)
        except IndexError:
            pass

from docx import Document
from docx.shared import Inches
from docx.shared import Pt

x = Document()
y = x.sections
outputSection = y[0]
outputSection.page_height = Inches(4)
outputSection.page_width = Inches(6)
for row, nestedList in output.items():
    for index, seat in enumerate(nestedList):
        par = x.add_paragraph()
        run = par.add_run(f'{row}, Seat {index}')
        font = run.font
        font.size = Pt(16)
        font.bold = True

        for name in seat:
            par = x.add_paragraph()
            run = par.add_run(name)
            font = run.font
            font.size = Pt(13)

        x.add_page_break()

x.save('lookKateiDidIt.docx')
示例#9
0
def main():
    repo = git.Repo(search_parent_directories=True)
    commit = repo.head.commit

    with open('define_template_test_project.py', 'r') as file:
        PROJECT_DEFINITION = file.read()

    if not os.path.exists(DOC_DIR):
        os.makedirs(DOC_DIR)
    try:
        project = signac.get_project(ext.PROJECT_DIR)
    except LookupError:
        print('The templates project could not be found. Try running '
              './extract_templates.py before this script.')
        raise

    sort_keys = list(sorted(project.detect_schema()))
    sort_attrs = ['sp.' + '.'.join(key) for key in sort_keys]

    def sort_key(job):
        values = []
        for attr in sort_attrs:
            try:
                values.append(attrgetter(attr)(job))
            except AttributeError:
                pass
        return [0 if v is None else v for v in values]

    environments = project.detect_schema()['environment'][str]
    for env in sorted(environments):
        env_name = env.split('.')[-1]
        document = docx.Document()

        # Add code style
        style = document.styles.add_style('Code', WD_STYLE_TYPE.PARAGRAPH)
        style.font.name = 'Monaco'
        style.font.size = Pt(8)
        style = document.styles.add_style('CodeChar', WD_STYLE_TYPE.CHARACTER)
        style.font.name = 'Monaco'
        style.font.size = Pt(8)

        document.add_heading(env_name, level=0)
        p = document.add_paragraph("Output at commit ")
        p.add_run('{}'.format(commit), style='CodeChar')
        document.add_heading("FlowProject Definition", level=1)
        p = document.add_paragraph(PROJECT_DEFINITION, style='Code')
        document.add_page_break()

        document.add_heading("Operations without bundling", level=1)
        query = {'environment': env, 'parameters.bundle': {'$exists': False}}
        for job in sorted(project.find_jobs(query), key=sort_key):
            process_job(document, job)

        document.add_heading("Operations with bundling", level=1)
        query = {'environment': env, 'parameters.bundle': {'$exists': True}}
        for job in sorted(project.find_jobs(query), key=sort_key):
            process_job(document, job)

        fn = os.path.join(DOC_DIR, "{env}.docx".format(env=env_name))
        document.save(fn)
        print("Generated document '{}'.".format(fn))
示例#10
0
def createDocShedule(group):
    columns = 26
    groupReal = 4438
    wordDocument = docx.Document()

    style = wordDocument.styles['Normal']
    font = style.font
    font.name = 'Times New Roman'

    wordDocument.add_heading(f"Журнал посещения занятий группы {groupReal}",
                             3).alignment = 1

    font.size = Pt(10)

    mod_document(wordDocument)
    table = wordDocument.add_table(rows=1, cols=columns)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '№ п.п.'
    hdr_cells[1].text = 'ФИО'
    hdr_cells[1].alignment = 1
    hdr_cells[0].alignment = 1

    table.style = 'Table Grid'

    row = table.add_row()
    row.cells[0].merge(hdr_cells[0])
    row.cells[1].merge(hdr_cells[1])

    i = 0
    users = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    k = 0

    table.cell(0, 2).merge(table.cell(0, 5)).text = "Понедельник"
    table.cell(0, 6).merge(table.cell(0, 9)).text = "Вторник"
    table.cell(0, 10).merge(table.cell(0, 13)).text = "Среда"
    table.cell(0, 14).merge(table.cell(0, 17)).text = "Четверг"
    table.cell(0, 18).merge(table.cell(0, 21)).text = "Пятница"
    table.cell(0, 22).merge(table.cell(0, 25)).text = "Суббота"

    for i in range(columns):
        table.cell(1, i).height = Cm(5)
        table.cell(1, i).height_rule = WD_ROW_HEIGHT_RULE.AUTO
        # table.cell(1, i).text=f'\n\n\n{i}'
        tr = row._tr
        trPr = tr.get_or_add_trPr()
        trHeight = OxmlElement('w:trHeight')
        trHeight.set(qn('w:val'), "2000")
        trHeight.set(qn('w:hRule'), "atLeast")
        trPr.append(trHeight)

    i = 0
    for user in users:
        row = table.add_row()
        row_cells = row.cells
        # row_cells[0].height = Cm(0.3)
        # row_cells[0].height_rule = WD_ROW_HEIGHT_RULE.AT_LEAST

        row_cells[0].text = f'{i}'
        row_cells[0].width = Cm(1.19)
        row_cells[1].text = f'Студент{i}'
        row_cells[1].width = Cm(6)
        i += 1

    for row in table.rows:
        row.height = Cm(0.5)
        row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY

    row = table.add_row()
    row_cells = row.cells
    for row in row_cells:
        row.height = Cm(5)
    row_cells[0].merge(row_cells[1]).text = "Подпись старосты\n\n"
    row = table.add_row()
    row_cells = row.cells
    row_cells[0].merge(row_cells[1]).text = "Подпись преподавателя\n\n"

    wordDocument.add_heading(f"Создано через бота vk.com/botraspisanie",
                             3).alignment = 2
    wordDocument.save("starosta_blank.docx")
示例#11
0
    def doc5(self):
        document = Document()
        section = document.sections[-1]
        section.left_margin = Cm(1)
        section.right_margin = Cm(1)

        obj_styles = document.styles
        obj_charstyle = obj_styles.add_style('CommentsStyle',
                                             WD_STYLE_TYPE.CHARACTER)
        obj_font = obj_charstyle.font
        obj_font.size = Pt(8)
        obj_font.name = 'Times New Roman'

        obj_charstyle = obj_styles.add_style('CommentsStyle2',
                                             WD_STYLE_TYPE.CHARACTER)
        obj_font = obj_charstyle.font
        obj_font.size = Pt(10)
        obj_font.name = 'Times New Roman'

        header = document.sections[0].header
        paragraph = header.add_paragraph()
        paragraph.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
        paragraph.add_run(self.env.user.company_id.name).bold = True

        paragraph = header.add_paragraph()
        paragraph.paragraph_format.alignment = WD_TABLE_ALIGNMENT.RIGHT
        paragraph.add_run('Registration No: ')
        paragraph.add_run(self.id_number or ' ').bold = True

        # paragraph = header.add_paragraph('Transcript', style='Intense Quote')
        # paragraph.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER

        header_table = header.add_table(1, 3, width=500)
        header_table.autofit = False

        A = header_table.cell(0, 0)
        pt = A.paragraphs[0]
        t = pt.text = ''
        pt.add_run("Student's Name: ", style='CommentsStyle').bold = True
        pt.add_run(self.name, style='CommentsStyle').bold = False
        pt.paragraph_format.space_before = Pt(0)
        pt.paragraph_format.space_after = Pt(0)

        paragraph = A.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run("Program: ", style='CommentsStyle').bold = True
        paragraph.add_run(self.program_id.name,
                          style='CommentsStyle').bold = False

        paragraph = A.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run("Plan: ", style='CommentsStyle').bold = True
        paragraph.add_run(self.program_id.name + ' Major',
                          style='CommentsStyle').bold = False

        B = header_table.cell(0, 2)
        pt = B.paragraphs[0]
        t = pt.text = ''
        pt.add_run("Father's Name: ", style='CommentsStyle').bold = True
        pt.add_run(self.father_name, style='CommentsStyle').bold = False
        pt.paragraph_format.space_before = Pt(0)
        pt.paragraph_format.space_after = Pt(0)

        cells = header_table.add_row().cells
        cells[0]._element.clear_content()
        table = cells[0].add_table(rows=0, cols=4)
        table.style = 'Table Grid'
        table.autofit = False

        set_table_width(table, [1.8, 5.3, 1.0, 1.0])
        add_row(table, ['Code', 'Title', 'CH', 'Grd'])

        cells[2]._element.clear_content()
        table = cells[2].add_table(rows=0, cols=4)
        table.alignment = WD_TABLE_ALIGNMENT.RIGHT
        table.style = 'Table Grid'
        table.autofit = False

        set_table_width(table, [1.8, 5.3, 1.0, 1.0])
        add_row(table, ['Code', 'Title', 'CH', 'Grd'])

        set_table_width(header_table, [9.4, 1.0, 9.4])

        footer = document.sections[0].footer
        footer.is_linked_to_previous = False

        pt = footer.paragraphs[0]
        pt.add_run(
            '"The Official Transcript carries the embossed stamp of the University"',
            style='CommentsStyle').bold = True
        pt.paragraph_format.space_before = Pt(0)
        pt.paragraph_format.space_after = Pt(0)

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run(
            'Transcript Prepared By: ---------------------------------------------',
            style='CommentsStyle').bold = False

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run(
            'Transcript Checked By: ---------------------------------------------',
            style='CommentsStyle').bold = False

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run('Date of Issue: ' + str(fields.Date.today()),
                          style='CommentsStyle').bold = False

        paragraph = footer.add_paragraph()
        paragraph.paragraph_format.space_before = Pt(0)
        paragraph.paragraph_format.space_after = Pt(0)
        paragraph.add_run(
            '"Errors and Omissions are subject to Subsequent rectification"',
            style='CommentsStyle').bold = True
        paragraph.add_run("\t\t\tController of Examinations",
                          style='CommentsStyle2').bold = True

        big_table = document.add_table(0, 1)
        big_table.autofit = False
        set_table_width(big_table, [9.5])

        for semester in self.semester_ids:
            row = big_table.add_row()

            tag = row._tr
            child = OxmlElement('w:cantSplit')  # Create arbitrary tag
            tag.append(child)

            cells = row.cells
            cells[0]._element.clear_content()

            # label = cells[0].add_paragraph()
            # label.paragraph_format.keep_with_next = True
            # label.paragraph_format.space_before = Pt(0)
            # label.paragraph_format.space_after = Pt(0)

            table = cells[0].add_table(rows=1, cols=4)
            table.style = 'Table Grid'

            a = table.cell(0, 0)
            b = table.cell(0, 3)
            A = a.merge(b)
            A.text = semester.academic_semester_id.name
            A.paragraphs[
                0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER

            for subject in semester.student_subject_ids:
                add_row(table, [
                    subject.subject_id.subject_id.code,
                    subject.subject_id.subject_id.name,
                    subject.subject_id.weightage, subject.grade
                ])

            set_table_width(table, [1.8, 5.5, 1.0, 1.0])
            transcript_border(table)

            row = table.add_row()
            row_border(row, b=False)
            a = table.cell(len(table.rows) - 1, 0)
            b = table.cell(len(table.rows) - 1, 3)
            A = a.merge(b)

            tb_cell_run = A.paragraphs[0].add_run()
            tb_cell_run.add_text("\tSCH: " + str(semester.credits))
            tb_cell_run.add_text("\t\tSGP: " +
                                 '{0:,.2f}'.format(semester.grade_points))
            tb_cell_run.add_text("\tSGPA: " + '{0:,.2f}'.format(semester.sgpa))
            tb_cell_run.font.size = Pt(8)

            row = table.add_row()
            # row_border(table.rows[len(table.rows)-1],t=False)
            row_border(row, t=False)
            a = table.cell(len(table.rows) - 1, 0)
            b = table.cell(len(table.rows) - 1, 3)
            A = a.merge(b)

            tb_cell_run = A.paragraphs[0].add_run()
            tb_cell_run.add_text("\tCCH: " + str(semester.cch))
            tb_cell_run.add_text("\t\tCGP: " + '{0:,.2f}'.format(semester.cgp))
            tb_cell_run.add_text("\tCGPA: " + '{0:,.2f}'.format(semester.cgpa))
            tb_cell_run.font.size = Pt(8)

            for row in table.rows:
                row.height = Cm(0.4)

            label = cells[0].paragraphs[0]
            label.paragraph_format.keep_with_next = True
            label.paragraph_format.space_before = Pt(0)
            label.paragraph_format.space_after = Pt(0)

        sectPr = document.sections[-1]._sectPr
        cols = sectPr.xpath('./w:cols')[0]
        cols.set(qn('w:num'), '2')

        preventDocumentBreak(document)

        # document.save('demo.docx')

        temporary_files = []

        doc_report_fd, doc_report_path = tempfile.mkstemp(suffix='.docx',
                                                          prefix='report.tmp.')
        os.close(doc_report_fd)
        temporary_files.append(doc_report_path)

        pdf_report_fd, pdf_report_path = tempfile.mkstemp(suffix='.pdf',
                                                          prefix='report.tmp.')
        os.close(pdf_report_fd)
        temporary_files.append(pdf_report_path)

        document.save(doc_report_path)

        #send to server
        headers = {
            'Content-Type': 'multipart/form-data',
        }

        response = requests.put(endpoint,
                                files={'file': open(doc_report_path, 'rb')})
        if response.status_code == 200:
            print(response.text)

        response = requests.get(endpoint2)
        print(response.status_code)

        if response.status_code == 200:
            with open(pdf_report_path,
                      'wb') as out_file:  # change file name for PNG images
                out_file.write(response.content)

        #
        # try:
        #     # wkhtmltopdf = [_get_wkhtmltopdf_bin()] + command_args + files_command_args + paths + [pdf_report_path]
        #     wkhtmltopdf = ["/usr/bin/unoconv", "-f", "pdf", "-o", pdf_report_path, doc_report_path]
        #     process = subprocess.Popen(wkhtmltopdf, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        #     out, err = process.communicate()
        # except:
        #     raise

        with open(pdf_report_path, 'rb') as pdf_document:
            pdf_content = pdf_document.read()

        # Manual cleanup of the temporary files
        for temporary_file in temporary_files:
            try:
                os.unlink(temporary_file)
            except (OSError, IOError):
                _logger.error('Error when trying to remove file %s' %
                              temporary_file)

        return pdf_content
    def handle_starttag(self, tag, attrs):
        if tag == EM:
            self.italic = True
        elif tag == P:
            if not self.list_level:
                self.paragraph = self.document.add_paragraph()
            paragraph_format = self.paragraph.paragraph_format
            paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
            paragraph_format.space_after = Pt(STANDART_PT)
            paragraph_format.first_line_indent = Cm(
                1.5)  # Inches(STANDART_INCHES + 0.3)
            #   paragraph_format.left_indent = Inches(STANDART_INCHES)
            paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
            if self.isBlockQuote:  # it's here because in html <blockquote><p></p></blockquote>
                paragraph_format.first_line_indent = Inches(0)
                paragraph_format.left_indent = Inches(STANDART_INCHES)
                paragraph_format.space_before = Pt(STANDART_PT)
                paragraph_format.space_after = Pt(STANDART_PT)
                paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
        elif tag == STRONG:
            self.bold = True
        elif tag in [H1, H2, H3, H4, H5, H6]:
            self.h = int(tag[1])
        elif tag == UL:
            self.list_level += 1
        elif tag == LI:
            self.paragraph = self.document.add_paragraph()
            self.need_dot_li = True
            self.font = self.normal_font
            self.size = self.normal_size
        elif tag == IMG:
            url = attrs[0][1]

            response = requests.get(url)
            picture = response.content
            with open(ABS_PATH.format(PICTURE_NAME), 'wb') as file:
                file.write(picture)
            try:
                self.document.add_picture(ABS_PATH.format(PICTURE_NAME),
                                          width=Inches(4),
                                          height=Inches(3))
                last_paragraph = self.document.paragraphs[-1]
                last_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                last_paragraph.space_after = Pt(10)
                last_paragraph.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE
                self.paragraph = self.document.add_paragraph()

                #last_paragraph.keep_with_next = False
            except Exception as e:
                print(e)
                print('ERROR WITH IMAGE {}'.format(url))
        elif tag == A:
            self.hyperlink = attrs[0][1]
        elif tag == BLOCKQUOTE:
            self.isBlockQuote = True
        # TABLE SECTION
        elif tag == TABLE:
            self.table_mode = True
        elif tag == THEAD:
            self.table_thead_mode = True
        elif tag == TH:
            pass
        elif tag == TR:
            if not self.table_thead_mode:
                self.table.add_row()
        elif tag == TD:
            pass
        # END TABLE SECTION
        elif tag == CODE:
            paragraph_format = self.paragraph.paragraph_format
            paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
            paragraph_format.line_spacing_rule = WD_LINE_SPACING.SINGLE
            paragraph_format.first_line_indent = Inches(0)
            self.italic = True
            self.size = self.code_size
            self.font = self.code_font
def usage_of_style_doc():
    document = Document()
    styles = document.styles
    table_styles = [s for s in styles if s.type == WD_STYLE_TYPE.TABLE]
    for style in table_styles:
        print(style.name)


    # 准备一些数据
    document = Document()
    vmem = psutil.virtual_memory()
    vmem_dict = vmem._asdict()
    trow = 2
    tcol = len(vmem_dict.keys())
    # 指定样式修饰表格
    table = document.add_table(rows=trow, cols=tcol, style='Colorful Grid Accent 4')
    for col, info in enumerate(vmem_dict.keys()):
        table.cell(0, col).text = info
        if info == 'percent':
            table.cell(1, col).text = str(vmem_dict[info]) + '%'
        else:
            table.cell(1, col).text = str(vmem_dict[info] / (1024 * 1024)) + 'M'
    document.save(PROJECT_PATH + "/file_location/table-style.docx")

    # 创建样式和设置字体
    doc = Document()
    for i in range(10):
        p = doc.add_paragraph(u'段落 % d' % i)
        style = doc.styles.add_style('UserStyle%d' % i, WD_STYLE_TYPE.PARAGRAPH)
        style.font.size = Pt(i + 20)
        p.style = style
    doc.save(PROJECT_PATH + '/file_location/style-1.docx')

    # 设置字体样式
    doc = Document()
    p = doc.add_paragraph()
    text_str = u'好好学习Python,努力做开发专家,成为最牛的程序员。'
    for i, ch in enumerate(text_str):
        run = p.add_run(ch)
        font = run.font
        font.name = u'微软雅黑'
        # bug of python-docx
        run._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑')
        font.bold = (i % 2 == 0)
        font.italic = (i % 3 == 0)
        color = font.color
        color.rgb = RGBColor(i * 10 % 200 + 55, i * 20 % 200 + 55, i * 30 % 200 + 55)
    doc.save(PROJECT_PATH + '/file_location/style-2.docx')

    # 设置段落格式
    doc = Document()
    for i in range(10):
        p = doc.add_paragraph(u'段落 % d' % i)
        style = doc.styles.add_style('UserStyle%d' % i, WD_STYLE_TYPE.PARAGRAPH)
        style.paragraph_format.left_indent = Cm(i)
        p.style = style

    doc.save(PROJECT_PATH + '/file_location/style-3.docx')


    # 样式管理器
    doc = Document()
    for i in range(10):
        p = doc.add_paragraph(u'段落 % d' % i)
        style = doc.styles.add_style('UserStyle%d' % i, WD_STYLE_TYPE.PARAGRAPH)
        style.paragraph_format.left_indent = Cm(i)
        p.style = style
        if i == 7:
            style.hidden = False
            style.quick_style = True

    for style in doc.styles:
        print(style.name, style.builtin)

    doc.paragraphs[3].style = doc.styles['Subtitle']
    doc.save(PROJECT_PATH + '/file_location/style-4.docx')
示例#14
0
def modify_to_docx(text, title):
    document = Document(
        'C:/Scrypti/Program/ScryptiTemplate/ScryptiTemplate.docx'
    )  #needs a template document in order to work. Template document cannot be empty.
    paragraph = document.paragraphs[0]
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None

    style = document.styles['Normal']
    font = style.font
    font.name = 'Segoe UI'
    font.size = Pt(10.5)
    titleparagraph = document.add_paragraph()
    titleparagraph.add_run('Captionmax Video Description Script' +
                           "\n").bold = True
    titleparagraph.add_run(title).bold = True

    titleparagraph_format = titleparagraph.paragraph_format
    titleparagraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

    descriptiontext = ''
    indescription = True
    counter = 0
    length = len(text)
    for character in text:
        counter += 1

        if character.isdigit() and text[counter].isdigit and text[counter +
                                                                  1] == ':':
            indescription = True

        elif (counter < length and character == '\n'
              and text[counter] == '\n') or counter == length:
            indescription = False

        if not indescription:
            indescription = True
            descriptiontext = descriptiontext[1:]
            descriptionparagraph = document.add_paragraph(descriptiontext)
            descriptiontext = ''
            descriptionparagraph_format = descriptionparagraph.paragraph_format
            descriptionparagraph_format.keep_together = True

        else:
            descriptiontext += character

        filename = ''
        firstnumber = True
        for character in title:
            if character.isalpha():
                filename += character
            elif character.isdigit() and firstnumber:
                filename += '-' + character
                firstnumber = False
            elif character.isdigit():
                filename += character
            elif character == ' ':
                filename = filename
            elif character == '&':
                filename += '_and_'

    savetitle = filename + '-VDS.docx'

    document.save("C:/Scrypti/Completed Files/%s" % savetitle)
示例#15
0
    cursor.execute("SHOW TABLES")
    rows = cursor.fetchall()
    tables = []

    for row in rows:
        tables.append(row)
    for table in tables:
        data = []
        cursor.execute("DESC " + table[0])
        rows = cursor.fetchall()
        for row in rows:
            data.append(row)

        paragraph = document.add_paragraph()
        paragraph.add_run(table[0]).font.size = Pt(21)

        form = document.add_table(rows=1, cols=6, style='Table Grid')
        hdr_cells = form.rows[0].cells
        hdr_cells[0].text = "字段名"
        hdr_cells[1].text = "长度"
        hdr_cells[2].text = "允许空值"
        hdr_cells[3].text = "键"
        hdr_cells[4].text = "虚拟"
        hdr_cells[5].text = "默认"
        for line in data:
            row_cells = form.add_row().cells
            row_cells[0].text = line[0]
            row_cells[1].text = line[1]
            row_cells[2].text = line[2]
            row_cells[3].text = line[3]
示例#16
0
    def make_puzzle(self, filename = 'puzzle'):
        difficulty = self.diff
        option = self.option
        if difficulty == 1:
            self.difficulty = 'random.choice([self.col, self.row])(word)'
        elif difficulty == 2:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev])(word)"
        elif difficulty == 3:
            self.difficulty = "random.choice([self.col, self.row, self.diagup, self.diagdown])(word)"
        elif difficulty == 4:
            self.difficulty = "random.choice([self.col, self.col_rev, self.row, self.row_rev, self.diagup, self.diagup_rev, self.diagdown, self.diagdown_rev])(word)"

        self.puzzle_origin = []
        for i in range(self.height):
            self.puzzle_origin.append([])
            for j in range(self.width):
                self.puzzle_origin[i].append('0')
        print("퍼즐 만드는 중")
        words = [word[0] for word in self.word_image]
        for word in words:
            exec(self.difficulty)

        string_words = ''.join(words)
        from collections import Counter
        count_alpha = Counter(string_words)

        common_alph = ''
        for alph in count_alpha.most_common(5):
            common_alph += alph[0]

        data = ''
        if self.korean:
            f = open("random_words.txt", 'r')
            data = f.read()
            regex_f = r'[가-힣]+'
            search_target_f = data
            data = ''.join(list(set(re.findall(regex_f, search_target_f))))

        printed_words = ''
        puzzle = copy.deepcopy(self.puzzle_origin)
        for i in range(self.height):
            for j in range(self.width):
                if self.puzzle_origin[i][j] == "0":
                    fill_alph = random.choice(string.ascii_lowercase)
                    if self.korean:
                        fill_alph = random.choice(data)
                    #글자들 되도록 겹치지 않게 하기 위해서 많이 나오는 글자 한번쯤은 피할 수 있도록 한다.
                    if option == 0:
                        puzzle[i][j] = fill_alph
                    elif option == 1:
                        if fill_alph in common_alph:
                            fill_alph = random.choice(string.ascii_lowercase)
                            if self.korean:
                                fill_alph = random.choice(data)
                        puzzle[i][j] = fill_alph
                        printed_words += puzzle[i][j]
                    #글자가 겹치도록 하기 위해서 많이 나온 글자와 무작위 글자들 중에서 고르도록 한다.
                    elif option == 2:
                        common_alph_list = []
                        puzzle[i][j] = random.choice([fill_alph, random.choice(count_alpha.most_common(7))[0]])
                    printed_words += puzzle[i][j]



        # write to docx file
        # Write to docx to puzzle.docx
        document = Document()
        #changing the page margins
        sections = document.sections
        for section in sections:
            section.top_margin = Cm(1)
            section.bottom_margin = Cm(0.8)
            section.left_margin = Cm(2.3)
            section.right_margin = Cm(2.3)
        heading = 'Word Puzzle'
        if self.korean:
            heading = "낱말 찾기"
        head = document.add_heading(heading, 0)
        head.alignment = WD_ALIGN_PARAGRAPH.CENTER
        if os.path.exists('hwp_settings.json'):
            with open('hwp_settings.json') as f:
                data = json.load(f)
                para_belong = document.add_paragraph('{}학년 {}반 이름: _______'.format(data['grade'], data['class']))
        else:
            para_belong = document.add_paragraph('__학년 __반 이름: _______')
        para_belong.alignment = WD_ALIGN_PARAGRAPH.RIGHT

        puzzle_table = document.add_table(rows=self.height, cols=self.width, style='Table Grid')
        puzzle_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        self.set_height = 7200 / self.height
        for i, row in enumerate(puzzle_table.rows):
            #######################세로 길이 정하기!
            # accessing row xml and setting tr height
            tr = row._tr
            trPr = tr.get_or_add_trPr()
            trHeight = OxmlElement('w:trHeight')
            trHeight.set(qn('w:val'), str(self.set_height))
            trHeight.set(qn('w:hRule'), "atLeast")
            trPr.append(trHeight)

            for j, cell in enumerate(row.cells):
                #####가로 길이 정하기!
                cell.width = Inches(5)
                if self.uppercase and not self.korean:
                    cell.text = puzzle[i][j].upper()
                else:
                    cell.text = puzzle[i][j]
                for paragraph in cell.paragraphs:
                    #####가운데 정렬!!
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    paragraph.style.font.bold = True
                #####상하 방향에서 가운데 정렬
                tc = cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

        # 힌트 테이블 만들기
        # 사진이 들어가는 경우
        if self.pic_on:
            word_num = len(words)
            if word_num <= 15:
                size = 5
            elif word_num <= 21:
                size = (word_num+2)//3
            else:
                size = 7
            hint_table = document.add_table(rows = (len(words)+size-1)//size * 2, cols = size, style = 'Table Grid')
            hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER

            for i, row in enumerate(hint_table.rows):
                #######################세로 길이 정하기!
                if i%2 == 0:
                    # accessing row xml and setting tr height
                    tr = row._tr
                    trPr = tr.get_or_add_trPr()
                    trHeight = OxmlElement('w:trHeight')
                    trHeight.set(qn('w:val'), '1000')
                    trHeight.set(qn('w:hRule'), "atLeast")
                    trPr.append(trHeight)
                elif i%2 == 1:
                    # accessing row xml and setting tr height
                    tr = row._tr
                    trPr = tr.get_or_add_trPr()
                    trHeight = OxmlElement('w:trHeight')
                    trHeight.set(qn('w:val'), '60')
                    trHeight.set(qn('w:hRule'), "atLeast")
                    trPr.append(trHeight)

                for j, cell in enumerate(row.cells):
                    index = i//2*size + j

                    #단어 수 만큼 반복하기
                    if index < len(words):
                        for paragraph in cell.paragraphs:
                            if i % 2 == 1:
                                # 초성 또는 scramble이 켜져 있는 경우
                                if self.chosung_scramable:
                                    word = words[index]
                                    if self.korean:
                                        cho_word = ''
                                        for chr in word:
                                            chosung_scramable = hgtk.letter.decompose(chr)[0]
                                            cho_word += chosung_scramable
                                        run = paragraph.add_run(cho_word)
                                    else:
                                        # 사진 있고 영어고 scramble인 경우
                                        spelling = [i for i in word]
                                        shuffle(spelling)
                                        scrambled_word = ''.join(spelling)
                                        if self.uppercase:
                                            run = paragraph.add_run(scrambled_word.upper())
                                        else:
                                            run = paragraph.add_run(scrambled_word)
                                else:
                                    if self.uppercase and not self.korean:
                                        run = paragraph.add_run(words[index].upper())
                                    else:
                                        run = paragraph.add_run(words[index])
                                font = run.font
                                font.name = 'Arial'
                                font.size = Pt(15)

                            elif i % 2 == 0:
                                try:
                                    run = paragraph.add_run()
                                    run.add_picture(self.word_image[index][1], width=cell.width *95/100,
                                                    height=cell.width)
                                except:
                                    paragraph.add_run("에러 발생. 다른 사진 선택해주세요.")


                            #####가운데 정렬!!
                            paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                            paragraph.style.font.bold = True
                    #####상하 방향에서 가운데 정렬
                    tc = cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)

        # 사진이 들어가지 않는 경우
        else:
            # 사진이 안 들어가고 영어인 경우
            if not self.korean:
                hint_table = document.add_table(rows=1, cols=1, style='Table Grid')
                hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                hint_table_row = hint_table.rows[0]
                hint_tr = hint_table_row._tr
                hint_trPr = hint_tr.get_or_add_trPr()
                hint_trHeight = OxmlElement('w:trHeight')
                hint_trHeight.set(qn('w:val'), '1000')
                hint_trHeight.set(qn('w:hRule'), "atLeast")
                hint_trPr.append(hint_trHeight)
                hint_table_cell = hint_table_row.cells[0]
                hint = ''
                parenthesis = re.compile(r'(\s)?\(.*\)(\s)?')
                bracket = re.compile(r'(\s)?\[.*\](\s)?')
                for word in words:
                    print("사전에 찾는중... " + word)
                    req = requests.get('http://endic.naver.com/small_search.nhn?query=' + word)
                    # 국어사전은 'http://ko.dict.naver.com/small_search.nhn?query='
                    html = req.text
                    soup = BeautifulSoup(html, 'html.parser')
                    meanings = soup.select('span.fnt_k05')
                    if self.uppercase:
                        word = word.upper()
                    if self.chosung_scramable:
                        spelling = [i for i in word]
                        shuffle(spelling)
                        word = ''.join(spelling)
                    if meanings:
                        text = meanings[0].text
                        text = re.sub(parenthesis, '', text)
                        text = re.sub(bracket, '', text)
                        print(text)
                        hint += word + "({})".format(text) + ', '
                hint_table_cell.width = Inches(100)
                for paragraph in hint_table_cell.paragraphs:
                    paragraph.add_run(hint.strip(', '))
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                tc = hint_table_cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

            else:
                # 사진이 안 들어가고 한글인 경우
                if self.chosung_scramable:
                    hint_table = document.add_table(rows=1, cols=1, style='Table Grid')
                    hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                    hint_table_row = hint_table.rows[0]
                    hint_tr = hint_table_row._tr
                    hint_trPr = hint_tr.get_or_add_trPr()
                    hint_trHeight = OxmlElement('w:trHeight')
                    hint_trHeight.set(qn('w:val'), '1000')
                    hint_trHeight.set(qn('w:hRule'), "atLeast")
                    hint_trPr.append(hint_trHeight)
                    hint_table_cell = hint_table_row.cells[0]
                    hint = ''
                    for word in words:
                        cho_word = ''
                        for chr in word:
                            chosung_scramable = hgtk.letter.decompose(chr)[0]
                            cho_word += chosung_scramable
                        hint += cho_word + ', '
                    hint_table_cell.width = Inches(100)
                    for paragraph in hint_table_cell.paragraphs:
                        paragraph.add_run(hint.strip(', '))
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                    tc = hint_table_cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)
                else:
                    hint_table = document.add_table(rows=1, cols=1, style='Table Grid')
                    hint_table.alignment = WD_TABLE_ALIGNMENT.CENTER
                    hint_table_row = hint_table.rows[0]
                    hint_tr = hint_table_row._tr
                    hint_trPr = hint_tr.get_or_add_trPr()
                    hint_trHeight = OxmlElement('w:trHeight')
                    hint_trHeight.set(qn('w:val'), '1000')
                    hint_trHeight.set(qn('w:hRule'), "atLeast")
                    hint_trPr.append(hint_trHeight)
                    hint_table_cell = hint_table_row.cells[0]
                    hint = ''
                    for word in words:
                        hint += word + ', '
                    hint_table_cell.width = Inches(100)
                    for paragraph in hint_table_cell.paragraphs:
                        paragraph.add_run(hint.strip(', '))
                        paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
                    tc = hint_table_cell._tc
                    tcPr = tc.get_or_add_tcPr()
                    tcVAlign = OxmlElement('w:vAlign')
                    tcVAlign.set(qn('w:val'), "center")
                    tcPr.append(tcVAlign)





        # 정답 파일 쓰기
        answ_doc = Document()
        answer_table = answ_doc.add_table(rows=self.height, cols=self.width, style='Table Grid')
        answer_table.alignment = WD_TABLE_ALIGNMENT.CENTER
        for i, row in enumerate(answer_table.rows):
            #######################세로 길이 정하기!
            # accessing row xml and setting tr height
            tr = row._tr
            trPr = tr.get_or_add_trPr()
            trHeight = OxmlElement('w:trHeight')
            trHeight.set(qn('w:val'), str(self.set_height))
            trHeight.set(qn('w:hRule'), "atLeast")
            trPr.append(trHeight)

            for j, cell in enumerate(row.cells):
                #####가로 길이 정하기!
                cell.width = Inches(8)
                cell.text = self.puzzle_origin[i][j]
                for paragraph in cell.paragraphs:
                    #####가운데 정렬!!
                    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    paragraph.style.font.bold = True
                    if cell.text == '0':
                        for run in paragraph.runs:
                            run.font.color.rgb = RGBColor(255, 255, 255)
                    else:
                        for run in paragraph.runs:
                            run.font.color.rgb = RGBColor(255, 0, 0)
                #####상하 방향에서 가운데 정렬
                tc = cell._tc
                tcPr = tc.get_or_add_tcPr()
                tcVAlign = OxmlElement('w:vAlign')
                tcVAlign.set(qn('w:val'), "center")
                tcPr.append(tcVAlign)

        answ_doc.save(str(self.desktop) + '\{}_정답.hwp'.format(filename))
        document.save(str(self.desktop) +'\{}.hwp'.format(filename))
        print("바탕화면에 puzzle.docx와 puzzle.hwp 로 저장")
示例#17
0
 def pcm(self, docx):
     add_analysis_paragraph(docx, self.add_analysis())
     paragraph = docx.add_paragraph()
     paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
     paragraph.paragraph_format.space_after = Pt(0)
     self.pcm_answer(paragraph)
示例#18
0
def stylize_paragraph(p):
    p.style.font.name = 'Book Antiqua'
    p.style.font.size = Pt(12)
    p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.from_xml('both')
示例#19
0
def wazuh():
    client = request.form['client']
    sujet = request.form['sujet']
    type = request.form['type']
    serv = request.form['serv']
    numero = request.form['numero']
    img = request.form['description']
    description = request.form['description']
    recommandation = request.form['recommandation']

    requete_wazuh = """INSERT INTO wazuh(type,numero,sujet,date,client,description,recommandation) VALUES(%s, %s, %s, %s, %s, %s)"""
    recordTuple = (type, numero, sujet, date, client, description,
                   recommandation)
    myCursor.execute(requete_wazuh, recordTuple)
    mydb.commit()

    doc = DocxTemplate("ATB_Template.docx")
    context = {'Keystone': "World company"}
    doc.render(context)
    parag = doc.add_paragraph()

    titre1 = parag.add_run("\t \t \t \tIncident ref: ")
    font = titre1.font
    font.name = 'Calibri (Body)'
    font.size = Pt(16)

    titre2 = parag.add_run(type + "-" + date + "-" + numero + "\n")
    font = titre2.font
    font.name = 'Calibri (Body)'
    font.size = Pt(16)
    font.bold = True

    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 128, 0)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    parag.add_run("\n")
    titre3 = parag.add_run("Sujet: " + sujet + "\n")
    if " " in sujet:
        sujet = sujet.replace(" ", "_")
    font = titre3.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True
    font.color.rgb = RGBColor(255, 255, 255)
    if (serv == "Elévé"):
        font.highlight_color = WD_COLOR_INDEX.RED
    elif (serv == "Moyenne"):
        font.highlight_color = WD_COLOR_INDEX.YELLOW
    else:
        font.highlight_color = WD_COLOR_INDEX.GREEN

    titre4 = parag.add_run("Réference: ")
    font = titre4.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    titre5 = parag.add_run(type + "-" + date + "-" + numero + "\n")
    font = titre5.font
    font.name = 'Calibri (Body)'
    font.size = Pt(16)
    font.bold = True

    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 128, 0)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    titre6 = parag.add_run("Sévirité: ")
    font = titre6.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    titre7 = parag.add_run(serv + "\n")
    font = titre7.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    if (serv == "Elévé"):
        font.color.rgb = RGBColor(255, 0, 0)
    elif (serv == "Moyenne"):
        font.color.rgb = RGBColor(255, 128, 0)
    else:
        font.color.rgb = RGBColor(0, 153, 0)

    titre8 = parag.add_run("Description:\n")
    font = titre8.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    titre9 = parag.add_run(description + "\n")
    font = titre9.font
    font.name = 'Calibri (Body)'
    font.size = Pt(12)

    titre11 = parag.add_run("Source :\n")
    font = titre11.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    titre12 = parag.add_run("Wazuh \n")
    font = titre12.font
    font.name = 'Calibri (Body)'
    font.size = Pt(12)

    titre13 = parag.add_run("Recommandation :\n")
    font = titre13.font
    font.name = 'Calibri (Body)'
    font.size = Pt(14)
    font.bold = True

    titre14 = parag.add_run(recommandation)
    font = titre14.font
    font.name = 'Calibri (Body)'
    font.size = Pt(12)

    doc.save(client + "-" + type + "-" + date + "-" + "0" + numero + "_" +
             sujet + ".docx")
    os.system("start " + client + "-" + type + "-" + date + "-" + "0" +
              numero + "_" + sujet + ".docx")
    return render_template('/wazuh.html')
示例#20
0
def gerar_oficios():

    wb = openpyxl.load_workbook(filename=plan_p)
    ws = wb[sl_assistido]

    if not os.path.exists(assistido):
        os.mkdir(assistido)
    #assistido = ws['A2'].value

    telefone = str(ws['M2'].value)

    none_count = 0
    for i in ws.iter_rows(min_row=2,
                          max_row=2,
                          min_col=1,
                          max_col=14,
                          values_only=True):  #melhor forma?
        for x in i:
            if x == None:
                none_count += 1

    if none_count != 0:
        print(
            f'Há {none_count} colunas vazias na planilha {assistido}. Preencha e salve a planilha novamente.'
        )
        return

    dados = f', cujo nome de registro é <<<nome de registro>>>, <<<nacionalidade>>>, <<<estado civil>>>, <<<ocupação>>>, IDENTIDADE n.º <<<identidade>>>, <<<órgão expedidor>>>, CPF: n.º <<<cpf>>>, residente na <<<endereço>>>, <<<bairro>>>, <<<cidade>>>, CEP: <<<cep>>>, '
    dados = dados.replace('<<<nome de registro>>>', ws['B2'].value)
    dados = dados.replace('<<<nacionalidade>>>', ws['C2'].value)
    dados = dados.replace('<<<estado civil>>>', ws['D2'].value)
    dados = dados.replace('<<<ocupação>>>', ws['E2'].value)
    dados = dados.replace('<<<identidade>>>', str(ws['F2'].value))
    dados = dados.replace('<<<órgão expedidor>>>', ws['G2'].value)
    dados = dados.replace('<<<cpf>>>', str(ws['H2'].value))
    dados = dados.replace('<<<endereço>>>', ws['I2'].value)
    dados = dados.replace('<<<bairro>>>', ws['J2'].value)
    dados = dados.replace('<<<cidade>>>', ws['K2'].value)
    dados = dados.replace('<<<cep>>>', str(ws['L2'].value))

    lista_cidades = []
    for i in ws.iter_rows(min_row=2,
                          max_row=30,
                          min_col=14,
                          max_col=14,
                          values_only=True):
        if i[0] != None:
            lista_cidades.append(i[0])

    lista_erros = [  #regex?
        'Rio de Janeiro ', 'rio de janeiro', 'rio de janeiro ',
        ' Rio de Janeiro', ' rio de janeiro', 'Rio de janeiro',
        ' Rio de janeiro', 'Rio de janeiro ', 'Belford Roxo ', ' Belford Roxo',
        'belford roxo', ' belford roxo', 'belford roxo ', 'Belford roxo',
        ' Belford roxo', 'Belford roxo ', 'Duque de Caxias ',
        ' Duque de Caxias', 'duque de caxias', ' duque de caxias',
        'duque de caxias ', 'Duque de caxias', ' Duque de caxias',
        'Duque de caxias ', ' Magé', 'Magé ', 'magé', 'magé ', ' magé', 'Mage',
        'Mage ', ' Mage', 'mage', ' mage', 'mage ', 'Niterói ', ' Niterói',
        'niterói', ' niterói', 'niterói ', 'Niteroi', 'Niteroi ', ' Niteroi',
        'niteroi', 'niteroi ', ' niteroi', 'Nova Iguaçu ', ' Nova Iguaçu',
        'Nova iguaçu', 'Nova iguaçu ', ' Nova iguaçu', 'nova iguaçu',
        'nova iguaçu ', ' nova iguaçu', 'São Gonçalo ', ' São Gonçalo',
        'São gonçalo', ' São gonçalo', 'São gonçalo ', 'são gonçalo',
        'são gonçalo ', ' são gonçalo', 'Sao Gonçalo', ' Sao Gonçalo',
        'Sao Gonçalo ', 'São João de Meriti ', ' São João de Meriti',
        ' São joão de meriti', 'São joão de meriti', 'São joão de meriti ',
        'são joão de meriti', ' são joão de meriti', 'são joão de meriti ',
        ' Seropédica', 'Seropédica ', 'seropédica', ' seropédica',
        'seropédica ', 'Seropedica', ' Seropedica', 'Seropedica ',
        'seropedica', ' seropedica', 'seropedica '
    ]

    subfolders = [f.name for f in os.scandir(diretorio)
                  if f.is_dir()]  #scandir usado pro ngc enorme la em cima?
    for i in lista_cidades:
        if i not in subfolders:
            if i not in lista_erros:
                print(
                    f'A célula {i} não foi reconhecida como uma cidade da lista de modelos. A pasta de modelos tem as seguintes sub-pastas: {subfolders}.\n\nCaso a cidade ESTEJA na lista, digite novamente, e salve a planilha de novo. Cuidado com erros de digitação.\n\nDo contrário, salve a planilha apenas com as cidades para as quais há modelos, e rode a célula abaixo para gerar os demais ofícios manualmente.'
                )
                return

    lista_oficios.append(padrao_zip)

    #nao tem como essa repeticao ser eficiente; olhar melhor o mecanismo
    if 'Rio de Janeiro' in lista_cidades or 'Rio de Janeiro ' in lista_cidades or 'rio de janeiro' in lista_cidades or 'rio de janeiro ' in lista_cidades or ' Rio de Janeiro' in lista_cidades or ' rio de janeiro' in lista_cidades or 'Rio de janeiro' in lista_cidades or ' Rio de janeiro' in lista_cidades or 'Rio de janeiro ' in lista_cidades:

        lista_oficios.append(z_rio)

    if 'Belford Roxo' in lista_cidades or 'Belford Roxo ' in lista_cidades or ' Belford Roxo' in lista_cidades or 'belford roxo' in lista_cidades or ' belford roxo' in lista_cidades or 'belford roxo ' in lista_cidades or 'Belford roxo' in lista_cidades or ' Belford roxo' in lista_cidades or 'Belford roxo ' in lista_cidades:

        lista_oficios.append(z_br)

    if 'Duque de Caxias' in lista_cidades or 'Duque de Caxias ' in lista_cidades or ' Duque de Caxias' in lista_cidades or 'duque de caxias' in lista_cidades or ' duque de caxias' in lista_cidades or 'duque de caxias ' in lista_cidades or 'Duque de caxias' in lista_cidades or ' Duque de caxias' in lista_cidades or 'Duque de caxias ' in lista_cidades:

        lista_oficios.append(z_dc)

    if 'Magé' in lista_cidades or ' Magé' in lista_cidades or 'Magé ' in lista_cidades or 'magé' in lista_cidades or 'magé ' in lista_cidades or ' magé' in lista_cidades or 'Mage' in lista_cidades or 'Mage ' in lista_cidades or ' Mage' in lista_cidades or 'mage' in lista_cidades or ' mage' in lista_cidades or 'mage ' in lista_cidades:

        lista_oficios.append(z_ma)

    if 'Niterói' in lista_cidades or 'Niterói ' in lista_cidades or ' Niterói' in lista_cidades or 'niterói' in lista_cidades or ' niterói' in lista_cidades or 'niterói ' in lista_cidades or 'Niteroi' in lista_cidades or 'Niteroi ' in lista_cidades or ' Niteroi' in lista_cidades or 'niteroi' in lista_cidades or 'niteroi ' in lista_cidades or ' niteroi' in lista_cidades:

        lista_oficios.append(z_nt)

    if 'Nova Iguaçu' in lista_cidades or 'Nova Iguaçu ' in lista_cidades or ' Nova Iguaçu' in lista_cidades or 'Nova iguaçu' in lista_cidades or 'Nova iguaçu ' in lista_cidades or ' Nova iguaçu' in lista_cidades or 'nova iguaçu' in lista_cidades or 'nova iguaçu ' in lista_cidades or ' nova iguaçu' in lista_cidades:

        lista_oficios.append(z_ni)

    if 'São Gonçalo' in lista_cidades or 'São Gonçalo ' in lista_cidades or ' São Gonçalo' in lista_cidades or 'São gonçalo' in lista_cidades or ' São gonçalo' in lista_cidades or 'São gonçalo ' in lista_cidades or 'são gonçalo' in lista_cidades or 'são gonçalo ' in lista_cidades or ' são gonçalo' in lista_cidades or 'Sao Gonçalo' in lista_cidades or ' Sao Gonçalo' in lista_cidades or 'Sao Gonçalo ' in lista_cidades:

        lista_oficios.append(z_sg)

    if 'São João de Meriti' in lista_cidades or 'São João de Meriti ' in lista_cidades or ' São João de Meriti' in lista_cidades or ' São joão de meriti' in lista_cidades or 'São joão de meriti' in lista_cidades or 'São joão de meriti ' in lista_cidades or 'são joão de meriti' in lista_cidades or ' são joão de meriti' in lista_cidades or 'são joão de meriti ' in lista_cidades:

        lista_oficios.append(z_sjm)

    if 'Seropédica' in lista_cidades or ' Seropédica' in lista_cidades or 'Seropédica ' in lista_cidades or 'seropédica' in lista_cidades or ' seropédica' in lista_cidades or 'seropédica ' in lista_cidades or 'Seropedica' in lista_cidades or ' Seropedica' in lista_cidades or 'Seropedica ' in lista_cidades or 'seropedica' in lista_cidades or ' seropedica' in lista_cidades or 'seropedica ' in lista_cidades:

        lista_oficios.append(z_sr)

    qtd_of = 0

    req = Document(diretorio + 'Padrão/Requerimento.docx')

    req.paragraphs[11].text = ''
    aa = req.paragraphs[11]
    um = aa.add_run(assistido)
    um.bold = True
    um.font.name = 'Arial'
    um.font.size = Pt(11)

    dois = aa.add_run(dados)
    dois.font.name = 'Arial'
    dois.font.size = Pt(11)

    tres = aa.add_run('telefone: ' + telefone + ' ')
    tres.font.name = 'Arial'
    tres.font.size = Pt(11)

    req.save(f'./{assistido}/Requerimento TRT.docx')

    anx = Document(diretorio + 'Padrão/Anexo 1° e 2° Grau.docx')
    anx.save(f'./{assistido}/Anexo 1° e 2° Grau.docx')

    for i in lista_oficios:
        for x in i:
            try:  #pq n jogar isso la pra cima?
                controle.save(ctrl_p)
            except PermissionError:
                print(
                    'A planilha do controle de ofícios está aberta. Feche o controle e rode esta célula novamente.'
                )
                return

            doc = x[0]
            caminho = x[1]

            n_atual = cs['F2'].value
            numero = n_atual + 1
            tabela = doc.tables[0]
            t1 = tabela.rows[0].cells[0]
            t2 = tabela.rows[0].cells[1]
            t1.text = ''
            p = t1.add_paragraph(
                f'Ofício n° {numero}/REQ/{ano}/NUDIVERSIS/DPGE/RJ')
            t2.text = ''
            q = t2.add_paragraph(f'Rio de Janeiro, {dia}/{mes}/{ano}')
            q.alignment = WD_ALIGN_PARAGRAPH.RIGHT

            for row in tabela.rows:
                for cell in row.cells:
                    paragraphs = cell.paragraphs
                    for paragraph in paragraphs:
                        for run in paragraph.runs:
                            run.font.name = 'Arial'
                            run.font.size = Pt(11)

            doc.paragraphs[11].text = ''
            aa = doc.paragraphs[11]
            um = aa.add_run(assistido)
            um.bold = True
            um.font.name = 'Arial'
            um.font.size = Pt(11)

            dois = aa.add_run(dados)
            dois.font.name = 'Arial'
            dois.font.size = Pt(11)

            doisemeio = aa.add_run('com a finalidade de ')
            doisemeio.font.name = 'Arial'
            doisemeio.font.size = Pt(11)

            tres = aa.add_run(
                'INSTRUIR PROCESSO ADMINISTRATIVO para retificação dos assentamentos civis.'
            )
            tres.font.name = 'Arial'
            tres.font.size = Pt(11)
            tres.bold = True
            tres.underline = True

            base = os.path.basename(caminho)
            cartorio = os.path.splitext(base)[0]

            cs.insert_rows(2)
            cs['F2'] = numero
            cs['G2'] = cartorio
            cs['H2'] = assistido
            cs['I2'] = 'Certidão Negativa'
            cs['J2'] = estagiario

            doc.save(
                f'./{assistido}/Ofício Nudiversis n. {numero}.Req.{ano} - ' +
                cs['G2'].value + f' - {assistido}.docx')
            controle.save(ctrl_p)
            qtd_of += 1

    print(f'Foram gerados {qtd_of} ofícios na pasta {assistido}. \n')
    cprint(
        'Lembre-se de mudar o PRENOME e o SEXO no documento Requerimento TRT.',
        attrs=['bold', 'underline'])
    return
示例#21
0
for file in filesnum:
    filename = str(input('מה יש בנספח ' + str(file) + '? '))
    document = Document()
    paragraph = document.add_paragraph()
    paragraph.alignment = 1
    style = document.styles['Normal']
    font = style.font
    p = document.add_paragraph()
    p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    paragraph.alignment = 1
    p.add_run('נספח ' + str(file)).bold = True
    c = document.add_paragraph(filename)
    c.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
    paragraph.alignment = 1
    font.name = 'David'
    font.size = Pt(64)
    filex = 'nispach ' + str(file) + '.docx'
    filepath = path + filex
    document.save(filepath)

import os
import win32com.client
import re
path = (r'C:\Users\User\Desktop\python\mypython\newfold')
word_file_names = []
word = win32com.client.Dispatch('Word.Application')
for dirpath, dirnames, filenames in os.walk(path):
    for f in filenames:
        if f.lower().endswith(".docx"):
            new_name = f.replace(".docx", ".pdf")
            in_file = (dirpath + '/' + f)
示例#22
0
def oficios_extra():

    if not os.path.exists(assistido):
        os.mkdir(assistido)

    wb = openpyxl.load_workbook(filename=plan_p)
    ws = wb[sl_assistido]

    quantos = int(input('De quantos ofícios você precisa? '))
    qtd_of = 0

    doc = Document(diretorio + 'Padrão/Modelo padrão.docx')

    dados = f', cujo nome de registro é <<<nome de registro>>>, <<<nacionalidade>>>, <<<estado civil>>>, <<<ocupação>>>, IDENTIDADE n.º <<<identidade>>>, <<<órgão expedidor>>>, CPF: n.º <<<cpf>>>, residente na <<<endereço>>>, <<<bairro>>>, <<<cidade>>>, CEP: <<<cep>>>, '
    dados = dados.replace('<<<nome de registro>>>', ws['B2'].value)
    dados = dados.replace('<<<nacionalidade>>>', ws['C2'].value)
    dados = dados.replace('<<<estado civil>>>', ws['D2'].value)
    dados = dados.replace('<<<ocupação>>>', ws['E2'].value)
    dados = dados.replace('<<<identidade>>>', str(ws['F2'].value))
    dados = dados.replace('<<<órgão expedidor>>>', ws['G2'].value)
    dados = dados.replace('<<<cpf>>>', str(ws['H2'].value))
    dados = dados.replace('<<<endereço>>>', ws['I2'].value)
    dados = dados.replace('<<<bairro>>>', ws['J2'].value)
    dados = dados.replace('<<<cidade>>>', ws['K2'].value)
    dados = dados.replace('<<<cep>>>', str(ws['L2'].value))

    while quantos != 0:
        n_atual = cs['F2'].value
        numero = n_atual + 1
        tabela = doc.tables[0]
        t1 = tabela.rows[0].cells[0]
        t2 = tabela.rows[0].cells[1]
        t1.text = ''
        p = t1.add_paragraph(
            f'Ofício n° {numero}/REQ/{ano}/NUDIVERSIS/DPGE/RJ')
        t2.text = ''
        q = t2.add_paragraph(f'Rio de Janeiro, {dia}/{mes}/{ano}')
        q.alignment = WD_ALIGN_PARAGRAPH.RIGHT

        for row in tabela.rows:
            for cell in row.cells:
                paragraphs = cell.paragraphs
                for paragraph in paragraphs:
                    for run in paragraph.runs:
                        run.font.name = 'Arial'
                        run.font.size = Pt(11)

        doc.paragraphs[11].text = ''
        aa = doc.paragraphs[11]
        um = aa.add_run(assistido)
        um.bold = True
        um.font.name = 'Arial'
        um.font.size = Pt(11)

        dois = aa.add_run(dados)
        dois.font.name = 'Arial'
        dois.font.size = Pt(11)

        doisemeio = aa.add_run('com a finalidade de ')
        doisemeio.font.name = 'Arial'
        doisemeio.font.size = Pt(11)

        tres = aa.add_run(
            'INSTRUIR PROCESSO ADMINISTRATIVO para retificação dos assentamentos civis.'
        )
        tres.font.name = 'Arial'
        tres.font.size = Pt(11)
        tres.bold = True
        tres.underline = True

        cs.insert_rows(2)
        cs['F2'] = numero
        cs['H2'] = assistido
        cs['I2'] = 'Certidão Negativa'
        cs['J2'] = estagiario

        doc.save(
            f'./{assistido}/Ofício Nudiversis n. {numero}.Req.{ano} - {assistido}.docx'
        )
        controle.save(ctrl_p)
        qtd_of += 1
        quantos -= 1

    print(f'\nForam gerados {qtd_of} ofícios adicionais na pasta {assistido}.')
    cprint(
        'Lembre-se de preencher os documentos com os cartórios e atualizá-los na planilha.',
        attrs=['bold', 'underline'])
    return
示例#23
0
    document.styles['Normal'].font.name = u'方正仿宋_GBK'
    document.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'),
                                                     u'方正仿宋_GBK')
    # today1 = time.strftime('%Y-%m-%d', time.localtime())
    #由于time库对中文支持不好,可以用以下方式处理
    today = time.strftime('%Y{y}%m{m}%d{d}', time.localtime()).format(y='年',
                                                                      m='月',
                                                                      d='日')
    # contract_name = input('请输入合同名称:')   #后续从数据库内筛选

    #编辑word内容
    p = document.add_paragraph()
    run_01 = p.add_run('xxxxxx有限公司\n合同款付款说明')
    run_01.font.name = u'方正小标宋_GBK'
    run_01.element.rPr.rFonts.set(qn('w:eastAsia'), '方正小标宋_GBK')
    run_01.font.size = Pt(22)  # 字体大小
    p.paragraph_format.line_spacing = Pt(28)  #行间距设置

    p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    #创建表格,并将表格在word页面中居中
    table = document.add_table(rows=5, cols=4, style="TableGrid")
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    # table.style.font.name = u'方正仿宋_GBK'
    textlist = [
        '合同/征收单位', '合同/规费名称', '合同/规费总价', '合同编号', '上期累计支付', '本期申请支付', '本期累计支付',
        '本期支付说明'
    ]
    n = 0
    for i in range(4):
        for j in (0, 2):
示例#24
0
document.add_page_break()

# draw circle
p = document.add_paragraph()
r = p.add_run()
img_size = 20
for x in range(255):
    im = Image.new('RGB', (img_size, img_size), 'white')
    draw_obj = ImageDraw.Draw(im)
    draw_obj.ellipse((0, 0, img_size - 1, img_size - 1), fill=255 - x)
    # save image to buffer
    fake_buf_file = BytesIO()
    im.save(fake_buf_file, "png")
    r.add_picture(fake_buf_file)
    fake_buf_file.close()

document.add_page_break()

# font with changing color
p = document.add_paragraph()
text = '一个人的命运当然要靠自我奋斗,但是也要考虑到历史的进程。'
for i, ch in enumerate(text):
    run = p.add_run(ch)
    font = run.font
    font.name = 'Silom'
    font.size = Pt(16)
    font.color.rgb = RGBColor(i * 10 % 200 + 55, i * 20 % 200 + 55,
                              i * 30 % 200 + 55)

document.save('ICanDo.docx')
示例#25
0
    def _write_static_p1(self) -> None:
        """Write the first part of the report before test result table.
        """
        para = self.doc.add_paragraph()
        self.add_line_break(para, 9, font_size=Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(22)
        run.add_text("Verification Summary report for Model")
        self.add_line_break(para, 4, font_size=Pt(14))

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("Record of changes")
        run.add_break()

        table = self.doc.add_table(rows=2, cols=4)
        for i in range(len(table.rows)):
            for j in range(len(table.columns)):
                run = table.rows[i].cells[j].paragraphs[0].add_run()
                run.bold = True
                run.font.size = Pt(14)

        table.style = "Table Grid"
        self.fill_table(table, [["Rev number", "Date", "Author", "Comments"], ["1", "", "<Name>", "Initial revision"]])

        para = self.doc.add_paragraph()
        self.add_line_break(para, 3, Pt(14))
        run = para.add_run()
        run.bold = True
        run.add_text("NOTE:")
        run = para.add_run()
        run.add_text(" Copies for use are available via the MyWorkshop system. Any printed copies are considered"
                     "uncontrolled. All approval signatures are captured electronically in MyWorkshop.")
        self.add_line_break(para, 9, Pt(14))

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("1   Introdction")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.bold = True
        run.add_text("1.1 Purpose & Scope")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.add_text(
            "This document contains the results of the verification for model for <name>. Tests were executed in "
            "accordance with the associated Verification Plan (DOC). ")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.bold = True
        run.add_text("1.2 References")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.add_text("Find below all the relevant documents related to any tools used during verification. ")

        table = self.doc.add_table(rows=4, cols=3)
        for i in range(len(table.rows)):
            for j in range(len(table.columns)):
                run = table.rows[i].cells[j].paragraphs[0].add_run()
                if i == 0:
                    run.bold = True

        table.style = "Table Grid"
        self.fill_table(
            table,
            [["Location", "Reference", "Document Name"], ["Myworkshop", "<DOC>", "Edison AI Model Verification Plan"], [
                "Myworkshop", "<DOC>", "Model Evaluation Tool Validation"
            ], ["Myworkshop", "<DOC>", "The CRS documents are in Approved state"]])

        para = self.doc.add_paragraph()
        self.add_line_break(para, 2, Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("2   Infrastructure Details")

        table = self.doc.add_table(rows=6, cols=2)
        for i in range(len(table.rows)):
            for j in range(len(table.columns)):
                run = table.rows[i].cells[j].paragraphs[0].add_run()
                if i == 0:
                    run.bold = True
        table.style = "Table Grid"
        self.fill_table(table,
                        [["", "Details"], ["GPU Architecture", ""], ["OS environment", ""], [
                            "Collection ID of test data set in Edison AI Workbench", ""
                        ], ["Model Artifact ID (s)", ""], ["Location of model test scripts", ""]])

        para = self.doc.add_paragraph()
        self.add_line_break(para, 2, Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("3   Verification Tools")

        para = self.doc.add_paragraph()
        run = para.add_run()
        run.add_text("Tools used for verification are listed in Model Evaluation Tool Validation <DOC>")

        para = self.doc.add_paragraph()
        self.add_line_break(para, 2, Pt(14))
        run = para.add_run()
        run.bold = True
        run.font.size = Pt(14)
        run.add_text("4   Results of Verification")

        table = self.doc.add_table(rows=2, cols=3)
        for i in range(len(table.rows)):
            for j in range(len(table.columns)):
                run = table.rows[i].cells[j].paragraphs[0].add_run()

        table.style = "Table Grid"
        self.fill_table(table,
                        [["Document", "Location", "Comments"],
                         ["<DOC>", "Myworkshop", "Verification Procedure is in Approved state"]])

        para = self.doc.add_paragraph()
        self.add_line_break(para, 1, Pt(14))
        run = para.add_run()
        run.bold = True
        run.add_text("4.1 Functional and Performance Tests")
示例#26
0
#! python3
# customInvite.py - create customized invite documents using names stored in a txt file
# author: Falak Jain

import docx
from docx.shared import Pt

doc = docx.Document()
with open('guests.txt') as guests:
    for guest_name in guests.readlines():
        p = doc.add_paragraph()
        p.add_run('It would be a pleasure to have the company of').italic = True
        p.alignment = 1
        p.style.font.size = Pt(16)
        p = doc.add_paragraph()
        p.add_run(guest_name.rstrip('\n')).italic = True
        p.alignment = 1
        p = doc.add_paragraph()
        p.add_run('at 11010 Memory Lane on the Evening of').italic = True
        p.alignment = 1
        p = doc.add_paragraph()
        p.add_run('April 1st').italic = True
        p.alignment = 1
        p = doc.add_paragraph()
        p.add_run("at 7 o'clock").italic = True
        p.alignment = 1
        doc.add_page_break()
doc.save('invite.docx')

示例#27
0
def ces(doc_title, doc_title_position, save_docx_name):
    document = Document()
    document.styles['Normal'].font.name = u'宋体'
    document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    '''
    section = document.sections[0]
    # 文档标题,默认在最左边
    if doc_title:
        # 设置选择标题
        header = section.header
        paragraph = header.paragraphs[0]

        # 如果选择了位置
        if doc_title_position:
            if doc_title_position == 'center':
                paragraph.text = '\t' + doc_title

            if doc_title_position == 'right':
                paragraph.text = '\t\t' + doc_title

            if doc_title_position == 'left':
                paragraph.text = doc_title

        # 默认在最左边
        else:
            paragraph.text = doc_title
    else:
        pass
    '''
    '''
    document.add_heading('')
    p = document.add_paragraph('', style='Heading 2')
    # 添加了一个段落,不是添加标题,只是在段落上添加文字
    p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    title = p.add_run(doc_title)
    title.font.name = u'宋体'
    title.bold = True
    title.font.size = Pt(15)
    title._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
'''
    filepath = './need/'
    for i, j, k in os.walk(filepath):

        for name in k:
            houzhui = name.split('.')[-1]
            if houzhui == 'png':

                document.add_heading('')
                p = document.add_paragraph('', style='Heading 2')
                # 添加了一个段落,不是添加标题,只是在段落上添加文字
                p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
                title = p.add_run(doc_title)
                title.font.name = u'宋体'
                title.bold = True
                title.font.size = Pt(15)
                title._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')

                path = filepath + name
                document.add_picture('{}'.format(path), width=Inches(6.5))

            if houzhui == 'txt':
                with open(filepath + name, 'r', encoding='utf-8') as f:
                    txt = f.read()
                    p2 = document.add_paragraph('')
                    # 整个段落使用首行缩进0.25厘米
                    p2.paragraph_format.first_line_indent = Inches(0.25)
                    # txt = '正月里采花无哟花采,二月间采花花哟正开,二月间采花花哟正开。三月里桃花红哟似海,四月间葡萄架哟上开,四月间葡萄架哟上开。'
                    text = p2.add_run(txt)
                    font = text.font
                    font.name = 'Calibri'
                    font.size = Pt(10.5)

            else:
                pass

    document.save(save_docx_name)
示例#28
0
def writedocxwithrealxls(file_path, filename, orders):
    document = Document()
    style = document.styles['Normal']
    font = style.font
    font.name = 'Times New Roman'
    font.size = Pt(9)
    for section in document.sections:
        section.orientation = 1 # 1 is LANDSCAPE, 0 is POTRAIT
        section.page_width = Mm(297) # for A4 Paper
        section.page_height = Mm(210)

        section.left_margin = Inches(0.5)
        section.right_margin = Inches(0.5)
        section.top_margin = Inches(0.5)
        section.bottom_margin = Inches(0.5)


    for item in orders:
        table = document.add_table(rows=0, cols=16)
        table.columns[0].width = Inches(0.45)
        table.columns[1].width = Inches(1.25)
        table.columns[2].width = Inches(1.65)
        table.columns[3].width = Inches(0.50)
        table.columns[4].width = Inches(0.55)
        table.columns[5].width = Inches(0.65)
        table.columns[6].width = Inches(0.75)
        table.columns[7].width = Inches(0.05)
        table.columns[8].width = Inches(0.05)
        table.columns[9].width = Inches(0.45)
        table.columns[10].width = Inches(1.25)
        table.columns[11].width = Inches(1.65)
        table.columns[12].width = Inches(0.50)
        table.columns[13].width = Inches(0.55)
        table.columns[14].width = Inches(0.65)
        table.columns[15].width = Inches(0.75)


        #Delivery Notes Title
        row_one = table.add_row().cells
        row_one[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        row_one[0].merge(row_one[6])
        row_one[0].paragraphs[0].add_run(item[0][0]).bold = True

        # Copy
        row_one[9].alignment = WD_ALIGN_PARAGRAPH.CENTER
        row_one[9].merge(row_one[15])
        row_one[9].paragraphs[0].add_run(item[0][0]).bold = True

        #Distributor Name, Customer Name, Order Number
        row_two = table.add_row().cells
        row_two[0].merge(row_two[1])
        row_two[0].text = item[1][0]
        row_two[0].paragraphs[0].add_run('\n' + item[2][0])
        row_two[2].text = item[1][1]
        row_two[2].paragraphs[0].add_run('\n' + item[2][1])
        row_two[2].paragraphs[0].add_run('\n' + item[3][0])
        row_two[2].paragraphs[0].add_run('\n' + item[4][0])
        row_two[3].merge(row_two[6])
        row_two[3].text = item[1][2]
        row_two[3].paragraphs[0].add_run('\n' + item[2][2])
        row_two[3].paragraphs[0].add_run('\n' + item[3][1])
        row_two[3].paragraphs[0].add_run('\n' + item[4][1])
        row_two[3].paragraphs[0].add_run('\n' + item[5][0])
        #Copy
        row_two[9].merge(row_two[10])
        row_two[9].text = item[1][0]
        row_two[9].paragraphs[0].add_run('\n' + item[2][0])
        row_two[11].text = item[1][1]
        row_two[11].paragraphs[0].add_run('\n' + item[2][1])
        row_two[11].paragraphs[0].add_run('\n' + item[3][0])
        row_two[11].paragraphs[0].add_run('\n' + item[4][0])
        row_two[12].merge(row_two[15])
        row_two[12].text = item[1][2]
        row_two[12].paragraphs[0].add_run('\n' + item[2][2])
        row_two[12].paragraphs[0].add_run('\n' + item[3][1])
        row_two[12].paragraphs[0].add_run('\n' + item[4][1])
        row_two[0].paragraphs[0].add_run('\n' + item[5][0])
        #Driver Message
        row_seven = table.add_row().cells
        row_seven[0].merge(row_seven[6])
        row_seven[0].text = item[6][0]
        #Copy
        row_seven[9].merge(row_seven[15])
        row_seven[9].text = item[6][0]
        # Product Detail Title
        row_nine = table.add_row().cells
        row_nine[0].merge(row_nine[6])
        row_table1 = row_nine[0].add_table(rows=0, cols=6)
        row_table1.style = 'TableGrid'
        row_table1.columns[0].width = Inches(0.45)
        row_table1.columns[1].width = Inches(2.0)
        row_table1.columns[2].width = Inches(0.50)
        row_table1.columns[3].width = Inches(0.55)
        row_table1.columns[4].width = Inches(0.65)
        row_table1.columns[5].width = Inches(0.75)
        row_table_cells1 = row_table1.add_row().cells
        row_table_cells1[0].paragraphs[0].add_run('Code').bold = True
        row_table_cells1[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        row_table_cells1[1].alignment = WD_ALIGN_PARAGRAPH.CENTER
        row_table_cells1[1].paragraphs[0].add_run('Description').bold = True
        row_table_cells1[2].paragraphs[0].add_run('UOM').bold = True
        row_table_cells1[3].paragraphs[0].add_run('QTY').bold = True
        row_table_cells1[4].paragraphs[0].add_run('Price').bold = True
        row_table_cells1[5].paragraphs[0].add_run('Amount').bold = True
        #Copy
        row_nine[9].merge(row_nine[15])
        row_table2 = row_nine[9].add_table(rows=0, cols=6)
        row_table2.style = 'TableGrid'
        row_table2.columns[0].width = Inches(0.45)
        row_table2.columns[1].width = Inches(2.0)
        row_table2.columns[2].width = Inches(0.50)
        row_table2.columns[3].width = Inches(0.55)
        row_table2.columns[4].width = Inches(0.65)
        row_table2.columns[5].width = Inches(0.75)
        row_table_cells2 = row_table2.add_row().cells
        row_table_cells2[0].paragraphs[0].add_run('Code').bold = True
        row_table_cells2[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        row_table_cells2[1].alignment = WD_ALIGN_PARAGRAPH.CENTER
        row_table_cells2[1].paragraphs[0].add_run('Description').bold = True
        row_table_cells2[2].paragraphs[0].add_run('UOM').bold = True
        row_table_cells2[3].paragraphs[0].add_run('QTY').bold = True
        row_table_cells2[4].paragraphs[0].add_run('Price').bold = True
        row_table_cells2[5].paragraphs[0].add_run('Amount').bold = True

        for products in item[8]:
            #Product Detail
            row_product1 = row_table1.add_row().cells
            row_product1[0].text = str(products[0]).replace('.0','')
            row_product1[1].text = str(products[1])
            row_product1[2].text = str(products[2])
            row_product1[3].text = str(products[3]).replace('.0','')
            row_product1[4].text = str(products[4]).replace('.0','')
            row_product1[5].text = str(products[5]).replace('.0','')
            #Copy
            row_product2 = row_table2.add_row().cells
            row_product2[0].text = str(products[0]).replace('.0','')
            row_product2[1].text = str(products[1])
            row_product2[2].text = str(products[2])
            row_product2[3].text = str(products[3]).replace('.0','')
            row_product2[4].text = str(products[4]).replace('.0','')
            row_product2[5].text = str(products[5]).replace('.0','')

        #Total Products
        row_eleven1 = row_table1.add_row().cells
        row_eleven1[0].text = ''
        row_eleven1[1].text = item[9][0]
        row_eleven1[2].text = ''
        row_eleven1[3].text = str(item[9][1]).replace('.0','')
        row_eleven1[4].text = ''
        row_eleven1[5].text = str(item[9][2]).replace('.0','')
        #Copy
        row_eleven2 = row_table2.add_row().cells
        row_eleven2[0].text = ''
        row_eleven2[1].text = item[9][0]
        row_eleven2[2].text = ''
        row_eleven2[3].text = str(item[9][1]).replace('.0','')
        row_eleven2[4].text = ''
        row_eleven2[5].text = str(item[9][2]).replace('.0','')

        #Tax Informaiton
        row_twelve = table.add_row().cells
        row_twelve[0].merge(row_twelve[6])
        row_twelve[0].text = item[10][0]
        #Copy
        row_twelve[9].merge(row_twelve[15])
        row_twelve[9].text = item[10][0]

        row_thirteen = table.add_row().cells
        row_fourteen = table.add_row().cells
        row_fifteen = table.add_row().cells
        #Buyer, Seller
        row_sixteen = table.add_row().cells
        row_sixteen[0].merge(row_sixteen[2])
        row_sixteen[0].text = item[11][0]
        row_sixteen[4].merge(row_sixteen[6])
        row_sixteen[4].text = item[11][1]
        #Copy
        row_sixteen[9].merge(row_sixteen[11])
        row_sixteen[9].text = item[11][0]
        row_sixteen[13].merge(row_sixteen[15])
        row_sixteen[13].text = item[11][1]

        document.add_page_break()

    document.save('%s%s.docx' % (file_path, filename))
示例#29
0
 def cm(self, docx):
     paragraph = docx.add_paragraph()
     paragraph.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
     paragraph.paragraph_format.space_after = Pt(0)
     self.cm_answer(paragraph)
     self.cm_ob(docx)
import gspread
import time
from oauth2client.service_account import ServiceAccountCredentials
from pprint import pprint
import docx
from docx.shared import Pt


document = docx.Document()
style = document.styles['Normal']
font = style.font
font.name = 'TimesNewRoman'
font.size = Pt(12)

p = document.add_paragraph()
r = p.add_run('Список представляемых к публикации докладов\n')
r.bold = True
r.italic = True
p.alignment = 1


document.add_paragraph('\tКафедра № 43 компьютерных технологий и программной инженерии')
document.add_paragraph('\tПоляк Марк Дмитриевич')
document.add_paragraph('\te-mail: [email protected]')
document.add_paragraph('\tтел.: +7-999-XXX-XXXX\n')



ex = []
delay1 = 60 #should be 60sec
delay2 = 0.1