Ejemplo n.º 1
0
def reset_paragraph_format(p, line_spacing: float = 1.05):
    ''' Reset paragraph format, especially line spacing.
        ---
        Args:
        - p: docx paragraph instance
        
        Two kinds of line spacing, corresponding to the setting in MS Office Word:
        - line_spacing=1.05: single or multiple
        - line_spacing=Pt(1): exactly
    '''
    pf = p.paragraph_format
    pf.line_spacing = line_spacing  # single by default
    pf.space_before = Pt(0)
    pf.space_after = Pt(0)
    pf.left_indent = Pt(0)
    pf.right_indent = Pt(0)
    pf.widow_control = True

    # do not adjust spacing between Chinese and Latin/number
    xml = r'<w:autoSpaceDE {} w:val="0"/>'.format(nsdecls('w'))
    p._p.get_or_add_pPr().insert(0, parse_xml(xml))

    xml = r'<w:autoSpaceDN {} w:val="0"/>'.format(nsdecls('w'))
    p._p.get_or_add_pPr().insert(0, parse_xml(xml))

    return pf
Ejemplo n.º 2
0
    def page_analiz_skad(self,
                         nom='YYYY.mm.dd-####-№№',
                         path='',
                         name='Анализ - СКАД',
                         head=None):
        self.wordDoc = Document(r'Analiz_SKAD.docx')
        style = self.wordDoc.styles['Normal']
        font = style.font
        font.name = 'Times New Roman'
        wd = self.wordDoc
        """Шаблон формирования шапки файла СКАД"""

        self.wordDoc.sections[0].header.is_linked_to_previous = False

        tx_all = self.wordDoc.sections[0].header.paragraphs[0].text
        tx_one = self.wordDoc.sections[0].first_page_header.paragraphs[0].text

        self.wordDoc.sections[0].header.paragraphs[0].text = tx_all.replace(
            '№YYYY.mm.dd-№№№№-## ', nom)
        self.wordDoc.sections[0].header.paragraphs[0].runs[0].font.size = Pt(
            10)
        self.wordDoc.sections[0].first_page_header.paragraphs[
            0].text = tx_one.replace('№YYYY.mm.dd-№№№№-## ', nom)
        self.wordDoc.sections[0].header.paragraphs[0].paragraphs[0].runs[
            0].font.size = Pt(10)

        tab = wd.add_table(2, 1)
        tab.cell(0, 0).text = head[0][0]
        tab.cell(0, 0).paragraphs[0].alignment = 2
        tab.cell(0, 0).paragraphs[0].runs[0].font.bold = True
        tab.cell(0, 0).paragraphs[0].paragraph_format.space_after = Pt(0)
        tab.cell(0, 1).text = head[1][0]
        tab.cell(0, 1).paragraphs[0].alignment = 2
        tab.cell(0, 1).paragraphs[0].runs[0].font.bold = True

        t1 = [[
            '1. Проведенные мероприятия по выявлению новых видов и случаев противоправных действий со сотрудников в отношении клиентов:'
        ], ['Анализ выставленных отклонений в СКАД ']]

        tab2 = wd.add_table(2, 1)
        tab2.style = 'TableGrid'
        tab2.cell(0, 0).text = t1[0][0]
        tab2.cell(0, 0).paragraphs[0].runs[0].font.bold = True
        tab2.cell(
            0,
            0).paragraphs[0].paragraph_format.first_line_indent = Inches(0.25)
        shadding_elm = parse_xml(r'<w:shd {} w:fill="A9A9A9"/>'.format(
            nsdecls('w')))
        tab2.cell(0, 0)._tc.get_or_add_tcPr().append(shadding_elm)
        tab2.cell(0, 1).text = t1[1][0]
        tab2.cell(
            0,
            1).paragraphs[0].paragraph_format.first_line_indent = Inches(0.25)
        shadding_elm = parse_xml(r'<w:shd {} w:fill="D9D9D9"/>'.format(
            nsdecls('w')))
        tab2.cell(0, 1)._tc.get_or_add_tcPr().append(shadding_elm)
Ejemplo n.º 3
0
def cell_colouring(cell, colour):
    if colour == 'R':
        colour = parse_xml(r'<w:shd {} w:fill="cb1f00"/>'.format(nsdecls('w')))
    elif colour == 'A/R':
        colour = parse_xml(r'<w:shd {} w:fill="f97b31"/>'.format(nsdecls('w')))
    elif colour == 'A':
        colour = parse_xml(r'<w:shd {} w:fill="fce553"/>'.format(nsdecls('w')))
    elif colour == 'A/G':
        colour = parse_xml(r'<w:shd {} w:fill="a5b700"/>'.format(nsdecls('w')))
    elif colour == 'G':
        colour = parse_xml(r'<w:shd {} w:fill="17960c"/>'.format(nsdecls('w')))

    cell._tc.get_or_add_tcPr().append(colour)
Ejemplo n.º 4
0
def add_data(table, course, content, date):
    indent = '                         '
    size = len(table.rows)
    table.add_row()
    table.cell(size, 0).text = indent + course
    table.cell(size, 1).text = content
    table.cell(size, 2).text = date
    table.cell(size, 0)._tc.get_or_add_tcPr().append(
        parse_xml(r'<w:shd {} w:fill="EEEEEE"/>'.format(nsdecls('w'))))
    table.cell(size, 1)._tc.get_or_add_tcPr().append(
        parse_xml(r'<w:shd {} w:fill="EEEEEE"/>'.format(nsdecls('w'))))
    table.cell(size, 2)._tc.get_or_add_tcPr().append(
        parse_xml(r'<w:shd {} w:fill="EEEEEE"/>'.format(nsdecls('w'))))
    def style_table(self, table, style):
        # Set styles and alignments
        table.style = style
        modulator = len(table.rows[0].cells)
        if style == "List Table 3":  # This is for the 1st table only
            min_row = 1
        else:
            min_row = 0

        index = 0
        for row in table.rows:
            for cell in row.cells:
                index += 1
                for para in cell.paragraphs:
                    para.style = self.document.styles['Normal in Table']
                    if index % modulator == 0:
                        if style == "List Table 2":
                            para.alignment = 2
                        else:
                            para.alignment = 0

                if index % modulator == 1:
                    if index > min_row:
                        shade_of_grey = parse_xml(
                            r'<w:shd {} w:fill="f0f0f0"/>'.format(
                                nsdecls('w')))
                        cell._tc.get_or_add_tcPr().append(shade_of_grey)

        for row in table.rows:
            self.set_cant_split(row)

        if style == "List Table 3":
            self.set_repeat_table_header(table.rows[0])
    def get_measure(self, measure_type_id):
        self.measure_type_id = measure_type_id
        self.get_measure_type_description()
        self.filename_template = "resources/measure_types/template/measure_type_template.docx"
        self.filename_docx = "resources/measure_types/measure_type_{measure_type_id}_{description}.docx".format(
            measure_type_id=self.measure_type_id,
            description=self.measure_type_description2)
        self.shade_of_grey = parse_xml(r'<w:shd {} w:fill="f0f0f0"/>'.format(
            nsdecls('w')))
        self.lipsum1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id porta orci. Suspendisse eget fringilla augue. Sed blandit iaculis odio, vel pharetra magna gravida id."
        self.lipsum2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id porta orci. Suspendisse eget fringilla augue. Sed blandit iaculis odio, vel pharetra magna gravida id."

        self.get_regulations()
        self.create_document()
        self.write_measure_type_description()
        self.add_background()
        self.add_measure_conditions()
        self.get_permutations()
        self.get_footnotes()
        self.get_geographies()
        self.get_chapters()
        self.get_headings()
        self.get_urls()

        # Save the file
        self.save_document()
Ejemplo n.º 7
0
def get_table_additional_questions():
    questions = [
        'Have you ever broken a rental agreement?',
        'Have you ever been evicted or asked to move?',
        'Have you ever refused to pay the rent?',
        'Have you ever filed for bankruptcy?',
        'Have you ever been convicted of a crime?',
        'Are any of the occupants smokers?'
    ]
    table_additional_questions = document.add_table(rows=12, cols=12)
    header_cell = get_merge_cells(table_additional_questions, 0, 0, 11)
    header_cell.text = 'ADDITIONAL QUESTIONS'
    table_header_color = parse_xml(r'<w:shd {} w:fill="#1f3864"/>'.format(nsdecls('w')))
    header_cell._tc.get_or_add_tcPr().append(table_header_color)

    table_additional_questions.autofit = False

    for row_number in range(1,12):
        if row_number%2 != 0:
            row_0_4 = get_merge_cells(table_additional_questions, row_number, 0, 4)
            row_0_4.text = questions[row_number//2]
            row_5_6 = get_merge_cells(table_additional_questions, row_number, 5, 6)
            row_5_6.text = f'YES {CHECK_BOX} NO {CHECK_BOX}'
            row_7_11 = get_merge_cells(table_additional_questions, row_number, 7, 11)
            row_7_11.text = ''
        else:
            row_0_2 = get_merge_cells(table_additional_questions, row_number, 0, 2)
            row_0_2.text = 'If yes, provide explanation'
            row_3_11 = get_merge_cells(table_additional_questions, row_number, 3, 11)
            set_cell_border(row_3_11, bottom={"sz": 6, "color": "#000000", "val": "single"})
Ejemplo n.º 8
0
def get_table_personal_references():
    table_personal_references = document.add_table(rows=3, cols=8)
    header_cell = get_merge_cells(table_personal_references, 0, 0, 7)
    header_cell.text = 'PERSONAL REFERENCES'
    table_header_color = parse_xml(r'<w:shd {} w:fill="#1f3864"/>'.format(nsdecls('w')))
    header_cell._tc.get_or_add_tcPr().append(table_header_color)

    table_personal_references.autofit = False

    second_row = table_personal_references.rows[1].cells
    second_row[0].text = 'Full Name'
    second_1_3_row = get_merge_cells(table_personal_references, 1, 1, 3)
    set_cell_border(second_1_3_row, bottom={"sz": 6, "color": "#000000", "val": "single"})
    second_row[4].text = 'Address'
    second_5_7_row = get_merge_cells(table_personal_references, 1, 5, 7)
    set_cell_border(second_5_7_row, bottom={"sz": 6, "color": "#000000", "val": "single"})

    third_row = table_personal_references.rows[2].cells
    third_row[0].text = 'Relationship'
    third_1_3_row = get_merge_cells(table_personal_references, 2, 1, 3)
    set_cell_border(third_1_3_row, bottom={"sz": 6, "color": "#000000", "val": "single"})
    third_row[4].text = 'Phone #'
    third_5_7_row = get_merge_cells(table_personal_references, 2, 5, 7)
    set_cell_border(third_5_7_row, bottom={"sz": 6, "color": "#000000", "val": "single"})

    paragraph = document.add_paragraph()
    paragraph.aligmnet = WD_TAB_ALIGNMENT
    paragraph_font = paragraph.style.font
    paragraph_font.name = 'Calibri'
    paragraph_font.size = Pt(10)
Ejemplo n.º 9
0
def get_table_additional_income():
    table_additional_income = document.add_table(rows=3, cols=6)

    for index, column in enumerate(table_additional_income.columns):
        for cell in column.cells:
            if index in [0, 4]:
                cell.width = Inches(1.25)
            elif index in [1]:
                cell.width = Inches(2.5)
            else:
                cell.width = Inches(0.9)

    i = 0
    get_merge_cells(table_additional_income, i, 0, len(table_additional_income.columns) - 1)

    current_row = table_additional_income.rows[i]

    table_header_color = parse_xml(r'<w:shd {} w:fill="#1f3864"/>'.format(nsdecls('w')))
    current_row.cells[0]._tc.get_or_add_tcPr().append(table_header_color)

    current_row.cells[0].text = 'additional income'.upper()

    for i in range(1,3):

        current_row = table_additional_income.rows[i]

        current_row.cells[0].text = 'Source of Income'
        current_row.cells[2].text = 'Amount $'
        current_row.cells[4].text = 'Proof of Income'
        current_row.cells[5].text = f'YES {CHECK_BOX} NO {CHECK_BOX}'

        set_cell_border(current_row.cells[1], bottom={"sz": 6, "color": "#000000", "val": "single"})
        set_cell_border(current_row.cells[3], bottom={"sz": 6, "color": "#000000", "val": "single"})
Ejemplo n.º 10
0
def get_table_additional_occupant(rows=4):
    table_additional_occupant = document.add_table(rows=rows, cols=7)

    table_additional_occupant.autofit = False

    paragraph = document.add_paragraph()
    paragraph.aligmnet = WD_TAB_ALIGNMENT
    paragraph_font = paragraph.style.font
    paragraph_font.name = 'Calibri'
    paragraph_font.size = Pt(10)


    header_cell = get_merge_cells(table_additional_occupant,0,0,6)
    header_cell.text = 'ADDITIONAL OCCUPANT(S)'
    table_header_color = parse_xml(r'<w:shd {} w:fill="#1f3864"/>'.format(nsdecls('w')))
    header_cell._tc.get_or_add_tcPr().append(table_header_color)


    for row in range(1, rows):
        column = table_additional_occupant.rows[row].cells
        column[0].text = 'Name'
        column[0].width = Inches(0.5)
        column_1_2 = get_merge_cells(table_additional_occupant, row, 1, 2)
        set_cell_border(column_1_2, bottom={"sz": 6, "color": "#000000", "val": "single"})

        column[3].text = 'Relationship'
        column[3].width = Inches(0.9)
        set_cell_border(column[4], bottom={"sz": 6, "color": "#000000", "val": "single"})

        column[5].text = 'Age'
        column[5].width = Inches(0.5)
        set_cell_border(column[6], bottom={"sz": 6, "color": "#000000", "val": "single"})
Ejemplo n.º 11
0
def set_char_shading(p_run, srgb: int):
    '''Set character shading color, in case the color is out of highlight color scope.
        ---
        Args:
        - p_run: docx.text.run.Run, proxy object wrapping <w:r> element
        - srgb: int, color value

        Read more:
        - http://officeopenxml.com/WPtextShading.php
    '''
    # try to set highlight first using python-docx built-in method
    # Here give 6/16 of the valid highlight colors
    color_map = {
        RGB_value((1, 0, 0)): WD_COLOR_INDEX.RED,
        RGB_value((0, 1, 0)): WD_COLOR_INDEX.BRIGHT_GREEN,
        RGB_value((0, 0, 1)): WD_COLOR_INDEX.BLUE,
        RGB_value((1, 1, 0)): WD_COLOR_INDEX.YELLOW,
        RGB_value((1, 0, 1)): WD_COLOR_INDEX.PINK,
        RGB_value((0, 1, 1)): WD_COLOR_INDEX.TURQUOISE
    }
    if srgb in color_map:
        p_run.font.highlight_color = color_map[srgb]

    # set char shading
    else:
        c = hex(srgb)[2:].zfill(6)
        xml = r'<w:shd {} w:val="clear" w:color="auto" w:fill="{}"/>'.format(
            nsdecls('w'), c)
        p_run._r.get_or_add_rPr().insert(0, parse_xml(xml))
def makeup_for_table(request_list, tables, color_list):
    table_num = 0
    try:
        for table in tables:
            request_dir_table = request_list[table_num]
            num_range = request_dir_table['Color']
            Start_row = request_dir_table['Start_row']
            Start_col = request_dir_table['Start_col']
            end_row = request_dir_table['end_row']
            end_col = request_dir_table['end_col']

            #將數據分為10組
            start, end = num_range[0], num_range[1]
            num_step_list = get_number_step(start, end)
            #背景著色
            for r in range(Start_row - 1, len(table.rows) + end_row + 1):
                for c in range(Start_col - 1,
                               len(table.columns) + end_col + 1):
                    text = table.cell(r, c).text
                    num = int(text)
                    for i in range(10):
                        if num_step_list[i][0] <= num < num_step_list[i][1]:
                            color_for_cell = color_list[i]
                    shading_elm_1 = parse_xml(
                        r'<w:shd {} w:fill="{color_value}"/>'.format(
                            nsdecls('w'), color_value=color_for_cell))

                    table.cell(r,
                               c)._tc.get_or_add_tcPr().append(shading_elm_1)
            table_num += 1
        msg = ''
        return msg
    except Exception as e:
        msg = '表格轉換失敗: ' + e
        return msg
Ejemplo n.º 13
0
def df_2_table(doc, df):
    row_num, col_num = df.shape
    t = doc.add_table(row_num + 1, col_num)
    t.alignment = WD_ALIGN_PARAGRAPH.RIGHT

    for j in range(col_num):
        # t.cell(0, j).text = df.columns[j]
        # paragraph = t.cell(0, j).add_paragraph()
        paragraph = t.cell(0, j).paragraphs[0]
        paragraph.add_run(df.columns[j]).bold = True
        paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

    # format table style to be a grid
    t.style = 'TableGrid'

    # populate the table with the dataframe
    for i in range(row_num):
        for j in range(col_num):
            # t.cell(i + 1, j).text = str(df.values[i, j])
            paragraph = t.cell(i + 1, j).paragraphs[0]
            paragraph.add_run(str(df.values[i, j])).bold = True
            paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT

    # Highlight all cells limegreen (RGB 32CD32) if cell contains text "0.5"
    from docx.oxml.ns import nsdecls
    from docx.oxml import parse_xml

    for i in range(1, row_num + 1):
        for j in range(col_num):
            if i % 2 == 0:
                t.cell(i, j)._tc.get_or_add_tcPr().append(
                    parse_xml(r'<w:shd {} w:fill="A3D9EA"/>'.format(nsdecls('w'))))
Ejemplo n.º 14
0
def get_table_pets_information():
    table_pets_information = document.add_table(rows=2, cols=13)
    header_cell = get_merge_cells(table_pets_information, 0, 0, 12)
    header_cell.text = 'pets information'.upper()
    table_header_color = parse_xml(r'<w:shd {} w:fill="#1f3864"/>'.format(nsdecls('w')))
    header_cell._tc.get_or_add_tcPr().append(table_header_color)

    table_pets_information.autofit = False

    row = table_pets_information.rows[1].cells
    row[0].text = 'Pet(s)'
    row_1_2 = get_merge_cells(table_pets_information, 1, 1, 2)
    row_1_2.text = f'YES {CHECK_BOX} NO {CHECK_BOX}'
    row_3_4 = get_merge_cells(table_pets_information, 1, 3, 4)
    row_3_4.text = 'Numbers of Pets'
    set_cell_border(row[5], bottom={"sz": 6, "color": "#000000", "val": "single"})
    row[6].text = 'Type'
    row_7_8 = get_merge_cells(table_pets_information, 1, 7, 8)
    set_cell_border(row_7_8, bottom={"sz": 6, "color": "#000000", "val": "single"})
    row[9].text = 'Breed'
    row_10_12 = get_merge_cells(table_pets_information, 1, 10, 12)
    set_cell_border(row_10_12, bottom={"sz": 6, "color": "#000000", "val": "single"})

    paragraph = document.add_paragraph()
    paragraph.aligmnet = WD_TAB_ALIGNMENT
    paragraph_font = paragraph.style.font
    paragraph_font.name = 'Calibri'
    paragraph_font.size = Pt(10)
Ejemplo n.º 15
0
 def write_trended_rank(self, responses):
     headers = self.max_groups(responses)
     table = self.doc.add_table(rows=1, cols=len(headers) + 4)
     titles_row = table.add_row().cells
     titles_row[1].merge(titles_row[2])
     headers_index = 0
     while headers_index < len(headers):
         header_text = "Total %s" % headers[headers_index]
         titles_row[headers_index + 4].text = header_text
         headers_index += 1
     first_row = True
     for response in responses:
         response_cells = table.add_row().cells
         response_cells[1].merge(response_cells[3])
         response_cells[1].text = response.response
         freq_col = 4
         if not response.frequencies:
             shading_elm = parse_xml(r'<w:shd {} w:fill="FFF206"/>'.format(
                 nsdecls('w')))
             response_cells[1]._tc.get_or_add_tcPr().append(shading_elm)
         for header in headers:
             if response.frequencies.get(header) is not None:
                 avg = response.frequencies.get(header)
                 text = self.avg_float(avg, first_row)
                 response_cells[freq_col].text = text
             first_row = False
             freq_col += 1
Ejemplo n.º 16
0
def get_table_vehicle_information():
    vehicle_information_text = [
        'Make', '', 'Model', '', 'Year', '', 'State', '', 'Plate #'
    ]
    table_vehicle_information = document.add_table(rows=3, cols=10)
    header_cell = get_merge_cells(table_vehicle_information, 0, 0, 9)
    header_cell.text = 'VEHICLE INFORMATION'
    table_header_color = parse_xml(r'<w:shd {} w:fill="#1f3864"/>'.format(
        nsdecls('w')))
    header_cell._tc.get_or_add_tcPr().append(table_header_color)

    table_vehicle_information.autofit = False

    for row_number in range(1, 3):
        row = table_vehicle_information.rows[row_number].cells
        for cell in range(10):
            if cell % 2 == 0:
                row[cell].text = vehicle_information_text[cell]
                row[cell].width = Inches(0.55)
            else:
                row[cell].width = Inches(1)
                set_cell_border(row[cell],
                                bottom={
                                    "sz": 6,
                                    "color": "#000000",
                                    "val": "single"
                                })

    paragraph = document.add_paragraph()
    paragraph.aligmnet = WD_TAB_ALIGNMENT
    paragraph_font = paragraph.style.font
    paragraph_font.name = 'Calibri'
    paragraph_font.size = Pt(10)
Ejemplo n.º 17
0
 def write_trended_allocate(self, sub_questions):
     headers = self.max_groups_subquestions(sub_questions)
     table = self.doc.add_table(rows=1, cols=len(headers) + 4)
     titles_row = table.add_row().cells
     titles_row[1].merge(titles_row[2])
     headers_index = 0
     while headers_index < len(headers):
         header_text = "Total %s" % headers[headers_index]
         titles_row[headers_index + 4].text = header_text
         headers_index += 1
     first_row = True
     for sub_question in sub_questions:
         for response in sub_question.responses:
             region_cells = table.add_row().cells
             region_cells[1].merge(region_cells[3])
             region_cells[1].text = "%s (n=%s)" % (sub_question.prompt,
                                                   sub_question.n)
             freq_col = 4
             if not response.frequencies:
                 shading_elm = parse_xml(
                     r'<w:shd {} w:fill="FFF206"/>'.format(nsdecls('w')))
                 region_cells[1]._tc.get_or_add_tcPr().append(shading_elm)
             for header in headers:
                 if response.frequencies.get(header) is not None:
                     freq = response.frequencies.get(header)
                     text = self.avgs_percent(freq, first_row)
                     region_cells[freq_col].text = text
                 else:
                     if first_row is True:
                         region_cells[freq_col].text = "$--"
                     else:
                         region_cells[freq_col].text = "--"
                 first_row = False
                 freq_col += 1
Ejemplo n.º 18
0
def set_char_scaling(p_run, scale:float=1.0):
    ''' Set character spacing: scaling. Font | Advanced | Character Spacing | Scaling.
        ---
        Args:
          - p_run: docx.text.run.Run, proxy object wrapping <w:r> element
          - scale: scaling factor
    '''
    p_run._r.get_or_add_rPr().insert(0, parse_xml(r'<w:w {} w:val="{}"/>'.format(nsdecls('w'), 100*scale)))
Ejemplo n.º 19
0
def tabBgColor(table, cols, colorStr):
    shading_list = locals()
    for i in range(cols):
        shading_list['shading_elm_' + str(i)] = parse_xml(
            r'<w:shd {} w:fill="{bgColor}"/>'.format(nsdecls('w'),
                                                     bgColor=colorStr))
        table.rows[0].cells[i]._tc.get_or_add_tcPr().append(
            shading_list['shading_elm_' + str(i)])
Ejemplo n.º 20
0
    def set_table_row_background_color(row):
        pending_quantity = float(row[3].text)
        ready_quantity = float(row[4].text)

        if ready_quantity >= pending_quantity:
            for cell in row:
                shading_elm_2 = parse_xml(
                    r'<w:shd {} w:fill="32CD32"/>'.format(nsdecls('w')))
                cell._tc.get_or_add_tcPr().append(shading_elm_2)
Ejemplo n.º 21
0
def make_doc_table(df, save_path, column_names=None, title=None, open=True):
    # Create doc
    doc = Document()
    style = doc.styles['Normal']
    font = style.font
    font.name = 'Calibri (Body)'
    font.size = Pt(10)

    # Add table title
    p = doc.add_paragraph('', style='No Spacing')
    p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.SINGLE
    sentence = p.add_run(title)
    sentence.font.size = Pt(8.5)
    sentence.font.bold = True
    sentence.font.italic = True

    # Add table
    nrows, ncols = df.shape
    table = doc.add_table(rows=nrows + 1,
                          cols=ncols)  #Add one more row for the header
    table.style = 'TableGrid'

    # Add header
    hdr_cells = table.rows[0].cells
    if column_names == None:
        column_names = df.columns
    for col_idx, col_name in enumerate(column_names):
        hdr_cells[col_idx].text = col_name
        hdr_cells[col_idx].paragraphs[0].runs[0].font.size = Pt(10)
        #hdr_cells[col_idx].paragraphs[0].runs[0].font.bold = True
        # Black shading
        black_shading = parse_xml(r'<w:shd {} w:fill="000000"/>'.format(
            nsdecls('w')))
        hdr_cells[col_idx]._tc.get_or_add_tcPr().append(black_shading)

    # Iterate through each row
    for row_idx, df_row in df.iterrows():
        row_idx = row_idx + 1
        # Iterate through each col
        for col_idx, col_val in enumerate(df_row):
            table.rows[row_idx].cells[col_idx].text = str(col_val)
            table.rows[row_idx].cells[col_idx].paragraphs[0].runs[
                0].font.size = Pt(8.5)
            table.rows[row_idx].cells[col_idx].paragraphs[0].runs[
                0].font.bold = False

    # Save
    doc.save(save_path)

    # Open
    if open:
        if sys.platform.startswith('darwin'):
            subprocess.call(('open', save_path))
        elif os.name == 'nt':  # For Windows
            os.startfile(save_path)
        elif os.name == 'posix':  # For Linux, Mac, etc.
            subprocess.call(('xdg-open', save_path))
Ejemplo n.º 22
0
def hostDocument(document, list1, list2):
    h1 = document.add_heading('3.主机巡检')
    count = 0
    text = ''
    for i in list2:
      if i:
          count += 1
    p1 = document.add_paragraph()
    run1 = p1.add_run("巡检小结:")
    run1.font.name = u'宋体'
    run1.font.size = Pt(11)
    text = "对主机CVK进行巡检,巡检异常项数:" + (str)(count) + ";" + "正常项数:" + (str)(len(list2) - count)
    p2 = document.add_paragraph()
    p2.paragraph_format.first_line_indent = Inches(0.3)
    run2 = p2.add_run(text)
    run2.font.name = u'宋体'
    run2.font.size = Pt(11)
    t1 = createTable(document, 8, 4)
    # 初始化表格
    t1.cell(0, 0).text = "检查内容"
    t1.cell(0, 1).text = "检查方法"
    t1.cell(0, 2).text = "检查结果"
    t1.cell(0, 3).text = "说明"
    t1.cell(1, 0).text = "*主机状态:\n*查看所有主机的运行状态。"
    t1.cell(1, 1).text = "在<云资源>的“主机”页面检查所有主" \
                         "机的运行状态是否显示“正常”"
    t1.cell(2, 0).text = "主机CPU占用率:查看所有主机CPU占用率,不超过80%"
    t1.cell(2, 1).text = "在<云资源>的“主机”页面检查所有主机的CPU占用率是否正常。"
    t1.cell(3, 0).text = "主机内存占用率:查看所有主机内存占用率,不超过80%。"
    t1.cell(3, 1).text = "在<云资源>的“主机”页面检查所有主机的内存占用率是否正常。"
    t1.cell(4, 0).text = "主机的磁盘和分区占用率:查看主机的磁盘和分区占用率,各个分区的占用率不超过80%。"
    t1.cell(4, 1).text = "在<云资源>/<主机池>/<集群>/<主机>的“性能监控”页面,查看“磁盘利用率”和“分区利用率”"
    t1.cell(5, 0).text = "主机的存储池:查看主机的存储池资源是否正常。\n*状态:活动"
    t1.cell(5, 1).text = "在<云资源>/<主机池>/<集群>/<主机>的“存储”页面,查看状态是否为“活动”,是否有足够的存储资源"
    t1.cell(6, 0).text = "主机的虚拟交换机:查看主机的虚拟交换机池资源是否正常。\n*状态:活动"
    t1.cell(6, 1).text = "在<云资源>/<主机池>/<集群>/<主机>的“虚拟交换机”页面,查看状态是否为“活动”,并且仅配置一个网关"
    t1.cell(7, 0).text = "主机的物理网卡:查看主机的物理网卡是否正常。" \
                         "\n*状态:活动\n*速率:与物理网卡实际速率保持一致" \
                         "\n*工作模式:full"
    t1.cell(7, 1).text = "在<云资源>/<主机池>/<集群>/<主机>的“物理网卡”" \
                         "页面,查看“状态”、“速率”以及“工作模式”是否正常。"

    # t1.cell(8, 0).text = "主机的FC HBA卡状态(可选):查看主机的FC HBA卡是否" \
    #                      "正常。\n*状态:活动\n*速率:与物理FC HBA卡实际速率保持一致"
    # t1.cell(8, 1).text = "在<云资源>/<主机池>/<集群>/<主机>的“FC HBA”" \
    #                      "页面,查看“状态”和“速率”是否正常。"

    # 参数赋值
    shading_elm_1 = parse_xml(r'<w:shd {} w:fill="FF0000"/>'.format(nsdecls('w')))
    for i in range(7):
        if not list2[i]:
            t1.cell(i + 1, 2).paragraphs[0].add_run(list1[i])
        else:
            run = t1.cell(i + 1, 2).paragraphs[0].add_run(list1[i])
            run.font.color.rgb = RGBColor(255, 0, 0)
            t1.cell(i + 1, 3).paragraphs[0].add_run(list2[i])
    return
Ejemplo n.º 23
0
def docx_fill_data(wdoc, data):
  
  items = data['items']
  total = data['total']

  table = wdoc.tables[1]

  def set_row_height(row):
    tr = row._tr
    trPr = tr.get_or_add_trPr()
    trHeight = OxmlElement('w:trHeight')
    trHeight.set(qn('w:val'), "250")
    trHeight.set(qn('w:hRule'), "atLeast")
    trPr.append(trHeight)

  int_format = '{:,}'
  decimal_format = '{:,.2f}'
  for item in items:
    row = table.add_row()
    set_row_height(row)
    cells = row.cells
    cells[0].text = int_format.format(item['quantity'])
    cells[1].text = str(item['description'])
    cells[2].text = decimal_format.format(item['unitprice'])
    cells[3].text = decimal_format.format(item['linetotal'])

    for x in range(4):
      if (x != 1):
        cells[x].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT

      cells[x].vertical_alignment = WD_ALIGN_VERTICAL.CENTER
      font = cells[x].paragraphs[0].runs[0].font
      font.size = Pt(8)

  row = table.add_row()
  cells = row.cells
  cells[2].text = str('Total')
  cells[3].text = decimal_format.format(total)

  for x in range(2, 4):
    cell = cells[x]
    font = cell.paragraphs[0].runs[0].font
    font.bold = True
    font.size = Pt(8)
    cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT

  background = parse_xml(r'<w:shd {} w:fill="E7EEEE"/>'.format(nsdecls('w')))
  index = 0
  for row in table.rows:
    index += 1
    if (index == 1 or index % 2 == 0):
      continue

    for cell in row.cells:
      cell._tc.get_or_add_tcPr().append(deepcopy(background))
Ejemplo n.º 24
0
def cells_background_color(table, value):
    # value = !11-15/*-12-15#00000F
    for elt in value.split('!'):
        area, color = elt.split('#')
        rows, columns = get_cells_coordinate(table, area)
        for i in rows:
            for j in columns:
                shading_elm_1 = parse_xml(r'<w:shd {} w:fill="{}"/>'.format(
                    nsdecls('w'), color))
                table.cell(i, j)._tc.get_or_add_tcPr().append(shading_elm_1)
Ejemplo n.º 25
0
def set_char_underline(p_run, srgb: int):
    '''Set underline and color.
        ---
        Args:
        - p_run: docx.text.run.Run, proxy object wrapping <w:r> element
        - srgb: int, color value
    '''
    c = hex(srgb)[2:].zfill(6)
    xml = r'<w:u {} w:val="single" w:color="{}"/>'.format(nsdecls('w'), c)
    p_run._r.get_or_add_rPr().insert(0, parse_xml(xml))
Ejemplo n.º 26
0
 def set_cell_background(self,cell,bk_color=None):
     '''
     设置单元格背景颜色
     cell:       _Cell对象,可通过get_cell函数获取
     bk_color:   RGB字符串,例如"AABBCC"
     '''
     xml = r'<w:shd {0} w:fill="{1}"/>'.format(nsdecls('w'),bk_color)
     # print(xml)
     shading_elm_1 = parse_xml(xml)
     cell._tc.get_or_add_tcPr().append(shading_elm_1)
Ejemplo n.º 27
0
def cell_colouring(word_table_cell: table.Table.cell, one, two) -> None:
    """Function that handles cell colouring for word documents"""

    try:
        if one != two:
            colour = parse_xml(r'<w:shd {} w:fill="cb1f00"/>'.format(
                nsdecls("w")))
            word_table_cell._tc.get_or_add_tcPr().append(colour)

    except TypeError:
        pass
Ejemplo n.º 28
0
def set_char_spacing(p_run, space:float=0.0):
    '''Set character spacing. 
    
    Manual operation in MS Word: Font | Advanced | Character Spacing | Spacing.
    
    Args:
        p_run (docx.text.run.Run): Proxy object wrapping <w:r> element.
        space (float, optional): Spacing value in Pt. Expand if positive else condense. Defaults to 0.0.
    '''
    p_run._r.get_or_add_rPr().insert(0, 
        parse_xml(r'<w:spacing {} w:val="{}"/>'.format(nsdecls('w'), 20*space)))
Ejemplo n.º 29
0
def set_char_scaling(p_run, scale:float=1.0):
    '''Set character spacing: scaling. 
    
    Manual operation in MS Word: Font | Advanced | Character Spacing | Scaling.
    
    Args:
        p_run (docx.text.run.Run): Proxy object wrapping <w:r> element.
        scale (float, optional): scaling factor. Defaults to 1.0.
    '''
    p_run._r.get_or_add_rPr().insert(0, 
        parse_xml(r'<w:w {} w:val="{}"/>'.format(nsdecls('w'), 100*scale)))
Ejemplo n.º 30
0
 def __call__(self, table):
     for row in table.rows:
         tp = parse_xml(r'<w:cantSplit {}/>'.format(nsdecls('w')))
         if row._tr.trPr is None:  # trPr为None的情况直接添加属性
             # print(tp, '--added')
             row._tr.get_or_add_trPr().append(tp)
         else:  # trPr不为None的情况下才做属性遍历,判断该属性是否已经存在
             for p in row._tr.trPr.getchildren():
                 # print(p, '--discovered')
                 if 'cantSplit' not in p.tag:
                     row._tr.get_or_add_trPr().append(tp)
Ejemplo n.º 31
0
 def with_nsdecls(self, *nspfxs):
     """
     Cause the element to contain namespace declarations. By default, the
     namespace prefixes defined in the Builder class are used. These can
     be overridden by providing exlicit prefixes, e.g.
     ``with_nsdecls('a', 'r')``.
     """
     if not nspfxs:
         nspfxs = self.__nspfxs__
     self._nsdecls = " %s" % nsdecls(*nspfxs)
     return self
Ejemplo n.º 32
0
def given_a_paragraph_with_content_and_formatting(context):
    p_xml = """\
        <w:p %s>
          <w:pPr>
            <w:pStyle w:val="%s"/>
          </w:pPr>
          <w:r>
            <w:t>foobar</w:t>
          </w:r>
        </w:p>""" % (nsdecls('w'), TEST_STYLE)
    p = parse_xml(p_xml)
    context.paragraph = Paragraph(p)
Ejemplo n.º 33
0
def given_a_run_having_mixed_text_content(context):
    """
    Mixed here meaning it contains ``<w:tab/>``, ``<w:cr/>``, etc. elements.
    """
    r_xml = """\
        <w:r %s>
          <w:t>abc</w:t>
          <w:tab/>
          <w:t>def</w:t>
          <w:cr/>
          <w:t>ghi</w:t>
          <w:drawing/>
          <w:br/>
          <w:t>jkl</w:t>
        </w:r>""" % nsdecls('w')
    r = parse_xml(r_xml)
    context.run = Run(r)
Ejemplo n.º 34
0
def docx_addpicture(document, path, width_mm, caption):
    paragraph = document.add_paragraph()
    paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = paragraph.add_run()
    run.add_picture(path, width=Mm(width_mm))
    # DOCX missing bookmarks
    # DOCX numbering goes next paragraph (WHY?)
    # See Issue: https://github.com/python-openxml/python-docx/issues/138
    if caption != "":
        paragraph = document.add_paragraph(style="Caption")
        p = paragraph._p  # this is the actual lxml element for a paragraph
        run = paragraph.add_run("Figure ")
        fld_xml = ('<w:fldSimple %s w:instr=" SEQ Figure \* ARABIC "/>' %
                   nsdecls('w'))
        fldSimple = parse_xml(fld_xml)  # this goes AFTER the field (!)
        #p.addnext(fldSimple)
        paragraph.add_run(" " + caption)
Ejemplo n.º 35
0
from docx import Document
from docx.shared import Cm

from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml

document = Document()

daystyle = "Normal"

border_elm_1_str = '''<w:tcBorders {}>
<w:top w:val="single" w:color="5C5C5C" w:space="0" w:sz="6"/>
<w:left w:val="single" w:color="5C5C5C" w:space="0" w:sz="6"/>
<w:bottom w:val="single" w:color="5C5C5C" w:space="0" w:sz="6"/>
<w:right w:val="single" w:color="5C5C5C" w:space="0" w:sz="6"/>
</w:tcBorders>'''.format(nsdecls('w'))

border_elm_2_str = '''<w:tcBorders {}>
<w:top w:val="single" w:color="BBBBBB" w:space="0" w:sz="6"/>
<w:left w:val="single" w:color="BBBBBB" w:space="0" w:sz="6"/>
<w:bottom w:val="single" w:color="BBBBBB" w:space="0" w:sz="6"/>
<w:right w:val="single" w:color="BBBBBB" w:space="0" w:sz="6"/>
</w:tcBorders>'''.format(nsdecls('w'))

cell_spacing_1_str = '''
<w:tblCellSpacing {} w:w="15" w:type="dxa"/>
'''.format(nsdecls('w'))

year = 2019
for month in range(1, 13):
    
Ejemplo n.º 36
0
# coding:utf-8
__author__ = 'uv2sun'

from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_TABLE_DIRECTION
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml

# Set a cell background (shading) color to RGB D9D9D9.
shading_elm = parse_xml(r'<w:shd {} w:fill="D9D9D9"/>'.format(nsdecls('w')))
print shading_elm
recordset = [
    {'qty': 'q1', 'id': 'id1', 'desc': 'desc1'},
    {'qty': 'q2', 'id': 'id2', 'desc': 'desc2'},
    {'qty': 'q3', 'id': 'id3', 'desc': 'desc3'}
]

document = Document()
table1 = document.add_table(rows=1, cols=3)
# table.style = ("ColorfulList", "TableGrid")
table1.style = 'TableGrid'

table1.alignment = WD_TABLE_ALIGNMENT.CENTER
table1.direction = WD_TABLE_DIRECTION.LTR

hdr_cells = table1.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'