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
def format(self) -> None: # center table within the page self.alignment = WD_TABLE_ALIGNMENT.CENTER # set column width for the patient details # 3cm is a good default width to fit dob and age on one line for cell in self.columns[1].cells: cell.width = Cm(3) # format the rows and cells for row in self.rows: # format the column headers and set header row to repeat if row.cells[0].text.lower() == "bed": for cell in row.cells: for paragraph in cell.paragraphs: for run in paragraph.runs: run.underline = True tr = row._tr trPr = tr.get_or_add_trPr() tblHeader = OxmlElement("w:tblHeader") tblHeader.set(qn("w:val"), "true") trPr.append(tblHeader) # format the ward headers if row.cells[0].text == row.cells[1].text: shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="EEEEEE"/>') for cell in row.cells: cell._tc.get_or_add_tcPr().append(shading_elm) # keep this header row on the same page as the next row for paragraph in cell.paragraphs: paragraph.paragraph_format.keep_with_next = True if "birthday" in row.cells[0].text: for cell in row.cells: for para in cell.paragraphs: for run in para.runs: run.italic = True # format new patients as bold if row._index in self._new_patient_indices: for cell in row.cells: for para in cell.paragraphs: for run in para.runs: run.bold = True # format all cells in the table for cell in row.cells: cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER for paragraph in cell.paragraphs: formatter = paragraph.paragraph_format formatter.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER formatter.space_before = Pt(2) formatter.space_after = Pt(2) # prevent table rows from splitting across page breaks no_split = parse_xml(f"<w:cantSplit {nsdecls('w')}/>") row._tr.get_or_add_trPr().append(no_split)
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)
def print_diff(from_part, to_part): print("-------\nDIFFING %s\n-------" % from_part.partname) from_xml = etree.tostring(parse_xml(from_part.blob), pretty_print=True, encoding=str) to_xml = etree.tostring(parse_xml(to_part.blob), pretty_print=True, encoding=str) open('a', 'w').write(from_xml) open('b','w').write(to_xml) diff = difflib.unified_diff(from_xml.split("\n"), to_xml.split("\n")) print("\n".join(diff))
def __init__(self, doc): self.doc = doc self.part = None self._element = None try: part = doc.part.package.part_related_by(RT.CUSTOM_PROPERTIES) except KeyError: self._element = parse_xml(self._part_template()) else: self.part = part self._element = parse_xml(part.blob)
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 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)
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 core_properties(self): element = parse_xml( b'<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\'?>' b'\n<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.o' b'rg/package/2006/metadata/core-properties" xmlns:dc="http://pur' b'l.org/dc/elements/1.1/" xmlns:dcmitype="http://purl.org/dc/dcm' b'itype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="h' b'ttp://www.w3.org/2001/XMLSchema-instance">\n' b' <cp:contentStatus>DRAFT</cp:contentStatus>\n' b' <dc:creator>python-docx</dc:creator>\n' b' <dcterms:created xsi:type="dcterms:W3CDTF">2012-11-17T11:07:' b'40-05:30</dcterms:created>\n' b' <dc:description/>\n' b' <dc:identifier>GXS 10.2.1ab</dc:identifier>\n' b' <dc:language>US-EN</dc:language>\n' b' <cp:lastPrinted>2014-06-04T04:28:00Z</cp:lastPrinted>\n' b' <cp:keywords>foo bar baz</cp:keywords>\n' b' <cp:lastModifiedBy>Steve Canny</cp:lastModifiedBy>\n' b' <cp:revision>4</cp:revision>\n' b' <dc:subject>Spam</dc:subject>\n' b' <dc:title>Word Document</dc:title>\n' b' <cp:version>1.2.88</cp:version>\n' b'</cp:coreProperties>\n' ) return CoreProperties(element)
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"})
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)
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)
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"})
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"})
def insert_cell_background(cell: _Cell, color_hex=DEFAULT_COLORED_CELL_COLOR) -> _Cell: """ Add a background color to a cell, from hex color """ shading_elm_1 = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{color_hex}"/>') cell._tc.get_or_add_tcPr().append(shading_elm_1) return cell
def add_column_fixture(self): snippets = snippet_seq('add-row-col') tbl = parse_xml(snippets[0]) table = Table(tbl, None) width = Inches(1.5) expected_xml = snippets[2] return table, width, expected_xml
def TableCellBackgroundColor(self, RowIndex, ColIndex, color="DDDDDD"): shading = parse_xml('<w:shd {} w:fill="DDDDDD"/>'.format( docx.oxml.ns.nsdecls('w'))) self.table.rows[RowIndex].cells[ColIndex]._tc.get_or_add_tcPr().append( shading) self.table.rows[RowIndex].cells[ColIndex].paragraphs[ 0].alignment = WD_ALIGN_PARAGRAPH.CENTER
def TableCellBGColor(self, cells, color="DDDDDD"): for r, c in cells: shading = parse_xml('<w:shd {} w:fill="DDDDDD"/>'.format( docx.oxml.ns.nsdecls('w'))) self.table.cell(r, c)._tc.get_or_add_tcPr().append(shading) self.table.cell( r, c).paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
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
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
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)
def custom_properties_blank(self): element = parse_xml( '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" ' 'xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">' '</Properties>\n' ) return CustomProperties(element)
def parse_xml_fragment(example_el, xml): """ Parse xml using example_el for namespace information. """ example_el = make_el(example_el, 'root') return list( parse_xml( etree.tostring(example_el, encoding=str)[:-2] + ">" + xml + "</root>"))
def new(cls): """ Return a new ``<Properties>`` element """ xml = cls._extendedProperties_tmpl extendedProperties = parse_xml(xml) return extendedProperties
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'))))
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
def new(cls): """ Return a new ``<cp:coreProperties>`` element """ xml = cls._coreProperties_tmpl coreProperties = parse_xml(xml) return coreProperties
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()
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)
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)
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)
def it_accepts_unicode_providing_there_is_no_encoding_declaration(self): non_enc_decl = '<?xml version="1.0" standalone="yes"?>' enc_decl = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' xml_body = '<foo><bar>føøbår</bar></foo>' # unicode body by itself doesn't raise parse_xml(xml_body) # adding XML decl without encoding attr doesn't raise either xml_text = '%s\n%s' % (non_enc_decl, xml_body) parse_xml(xml_text) # but adding encoding in the declaration raises ValueError xml_text = '%s\n%s' % (enc_decl, xml_body) with pytest.raises(ValueError): parse_xml(xml_text)
def element(self): return parse_xml('<foø><bår>text</bår></foø>')
def cells_fixture(self, request): snippet_idx, cell_count, unique_count, matches = request.param tbl_xml = snippet_seq('tbl-cells')[snippet_idx] table = Table(parse_xml(tbl_xml), None) return table, cell_count, unique_count, matches
def revision_get_fixture(self, request): str_val, expected_revision = request.param tagname = '' if str_val is None else 'cp:revision' coreProperties = self.coreProperties(tagname, str_val) core_properties = CoreProperties(parse_xml(coreProperties)) return core_properties, expected_revision
def date_prop_set_fixture(self, request): prop_name, tagname, value, str_val, attrs = request.param coreProperties = self.coreProperties(None, None) core_properties = CoreProperties(parse_xml(coreProperties)) expected_xml = self.coreProperties(tagname, str_val, attrs) return core_properties, prop_name, value, expected_xml
def element(self): """ Element parsed from XML generated by builder in current state """ elm = parse_xml(self.xml()) return elm
def new(cls, package): """Return newly created header part.""" partname = package.next_partname("/word/header%d.xml") content_type = CT.WML_HEADER element = parse_xml(cls._default_header_xml()) return cls(partname, content_type, element, package)
def it_determines_class_used_for_elements_with_matching_tagname( self, xml_text): register_element_cls('a:foo', CustElmCls) foo = parse_xml(xml_text) assert type(foo) is CustElmCls assert type(foo.find(qn('a:bar'))) is etree._Element
def it_accepts_bytes_and_assumes_utf8_encoding(self, xml_bytes): parse_xml(xml_bytes)
def _snippet_tbl(self, idx): """ Return a <w:tbl> element for snippet at *idx* in 'tbl-cells' snippet file. """ return parse_xml(snippet_seq('tbl-cells')[idx])
# 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'
def tc_raise_fixture(self, request): snippet_idx, row_idx, col_idx = request.param tbl = parse_xml(snippet_seq('tbl-cells')[snippet_idx]) tr = tbl.tr_lst[row_idx] return tr, col_idx
def it_uses_registered_element_classes(self, xml_bytes): register_element_cls('a:foo', CustElmCls) element = parse_xml(xml_bytes) assert isinstance(element, CustElmCls)
def add_row_fixture(self): snippets = snippet_seq('add-row-col') tbl = parse_xml(snippets[0]) table = Table(tbl, None) expected_xml = snippets[1] return table, expected_xml
def revision_set_fixture(self, request): value, str_val = request.param coreProperties = self.coreProperties(None, None) core_properties = CoreProperties(parse_xml(coreProperties)) expected_xml = self.coreProperties('cp:revision', str_val) return core_properties, value, expected_xml
def element(cxel_str): """ Return an oxml element parsed from the XML generated from *cxel_str*. """ _xml = xml(cxel_str) return parse_xml(_xml)
<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): table = document.add_table(rows=12, cols=7) # print(table._tbl) cell_spacing_1 = parse_xml(cell_spacing_1_str) table._tbl.tblPr.append(cell_spacing_1) # header hdr_cells = table.rows[0].cells hdr_cells[0].merge(hdr_cells[6]) hdr_cells[0].text = '%d-%d'%(year, month) # Monday to Sunday week_cells = table.rows[1].cells for i, m in enumerate(['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']): week_cells[i].text = m.decode('utf-8') # Others for i in range(5): rowid_week = 2 + i*2
def add_footnotes(self, doc, element): """Add footnotes from the given document used in the given element.""" footnotes_refs = element.findall('.//w:footnoteReference', NS) if not footnotes_refs: return footnote_part = doc.part.rels.part_with_reltype(RT.FOOTNOTES) my_footnote_part = self.footnote_part() footnotes = parse_xml(my_footnote_part.blob) next_id = len(footnotes) + 1 for ref in footnotes_refs: id_ = ref.get('{%s}id' % NS['w']) element = parse_xml(footnote_part.blob) footnote = deepcopy( element.find('.//w:footnote[@w:id="%s"]' % id_, NS)) footnotes.append(footnote) footnote.set('{%s}id' % NS['w'], str(next_id)) ref.set('{%s}id' % NS['w'], str(next_id)) next_id += 1 self.add_referenced_parts(footnote_part, my_footnote_part, element) my_footnote_part._blob = serialize_part_xml(footnotes)