def to_tree(self, tagname): """ Return as XML node """ el = Element(tagname) el.text = unicode(self) return el
def to_tree(self): tree = Element("Relationships", xmlns=PKG_REL_NS) for idx, rel in enumerate(self.Relationship, 1): if not rel.Id: rel.Id = "rId{0}".format(idx) tree.append(rel.to_tree()) return tree
def to_tree(self, tagname=None, idx=None): parent = Element("fill") el = Element(self.tagname) if self.patternType is not None: el.set('patternType', self.patternType) for c in self.__elements__: value = getattr(self, c) if value != Color(): el.append(value.to_tree(c)) parent.append(el) return parent
def to_tree(self, tagname, obj, namespace=None): """ Convert the sequence represented by the descriptor to an XML element """ for idx, v in enumerate(obj, self.idx_base): if hasattr(v, "to_tree"): el = v.to_tree(tagname, idx) else: tagname = namespaced(obj, tagname, namespace) el = Element(tagname) el.text = safe_string(v) yield el
def _shape_factory(row, column, height, width): style = ("position:absolute; " "margin-left:59.25pt;" "margin-top:1.5pt;" "width:{width}px;" "height:{height}px;" "z-index:1;" "visibility:hidden").format(height=height, width=width) attrs = { "type": "#_x0000_t202", "style": style, "fillcolor": "#ffffe1", "{%s}insetmode" % officens: "auto" } shape = Element("{%s}shape" % vmlns, attrs) SubElement(shape, "{%s}fill" % vmlns, {"color2": "#ffffe1"}) SubElement(shape, "{%s}shadow" % vmlns, { "color": "black", "obscured": "t" }) SubElement(shape, "{%s}path" % vmlns, {"{%s}connecttype" % officens: "none"}) textbox = SubElement(shape, "{%s}textbox" % vmlns, {"style": "mso-direction-alt:auto"}) SubElement(textbox, "div", {"style": "text-align:left"}) client_data = SubElement(shape, "{%s}ClientData" % excelns, {"ObjectType": "Note"}) SubElement(client_data, "{%s}MoveWithCells" % excelns) SubElement(client_data, "{%s}SizeWithCells" % excelns) SubElement(client_data, "{%s}AutoFill" % excelns).text = "False" SubElement(client_data, "{%s}Row" % excelns).text = str(row) SubElement(client_data, "{%s}Column" % excelns).text = str(column) return shape
def _explicit_none(tagname, value, namespace=None): """ Override serialisation because explicit none required """ if namespace is not None: tagname = "{%s}%s" % (namespace, tagname) return Element(tagname, val=safe_string(value))
def test_write_style(self): root = Element("{%s}test" % CHART_DRAWING_NS) self.sw._write_style(root) xml = tostring(root) expected = """<cdr:test xmlns:cdr="http://schemas.openxmlformats.org/drawingml/2006/chartDrawing"><cdr:style><a:lnRef idx="2" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:schemeClr val="accent1"><a:shade val="50000" /></a:schemeClr></a:lnRef><a:fillRef idx="1" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:schemeClr val="accent1" /></a:fillRef><a:effectRef idx="0" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:schemeClr val="accent1" /></a:effectRef><a:fontRef idx="minor" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:schemeClr val="lt1" /></a:fontRef></cdr:style></cdr:test>""" diff = compare_xml(xml, expected) assert diff is None, diff
def test_write_text(self): root = Element("{%s}test" % CHART_DRAWING_NS) self.sw._write_text(root, self.shape) xml = tostring(root) expected = """<cdr:test xmlns:cdr="http://schemas.openxmlformats.org/drawingml/2006/chartDrawing"><cdr:txBody><a:bodyPr vertOverflow="clip" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /><a:lstStyle xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" /><a:p xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:r><a:rPr lang="en-US"><a:solidFill><a:srgbClr val="000000" /></a:solidFill></a:rPr><a:t>My first chart</a:t></a:r></a:p></cdr:txBody></cdr:test>""" diff = compare_xml(xml, expected) assert diff is None, diff
def write(self, shape_id): root = Element('{%s}userShapes' % CHART_NS) for shape in self._shapes: anchor = SubElement(root, '{%s}relSizeAnchor' % CHART_DRAWING_NS) xstart, ystart, xend, yend = shape.coordinates _from = SubElement(anchor, '{%s}from' % CHART_DRAWING_NS) SubElement(_from, '{%s}x' % CHART_DRAWING_NS).text = str(xstart) SubElement(_from, '{%s}y' % CHART_DRAWING_NS).text = str(ystart) _to = SubElement(anchor, '{%s}to' % CHART_DRAWING_NS) SubElement(_to, '{%s}x' % CHART_DRAWING_NS).text = str(xend) SubElement(_to, '{%s}y' % CHART_DRAWING_NS).text = str(yend) sp = SubElement(anchor, '{%s}sp' % CHART_DRAWING_NS, { 'macro': '', 'textlink': '' }) nvspr = SubElement(sp, '{%s}nvSpPr' % CHART_DRAWING_NS) SubElement(nvspr, '{%s}cNvPr' % CHART_DRAWING_NS, { 'id': str(shape_id), 'name': 'shape %s' % shape_id }) SubElement(nvspr, '{%s}cNvSpPr' % CHART_DRAWING_NS) sppr = SubElement(sp, '{%s}spPr' % CHART_DRAWING_NS) frm = SubElement( sppr, '{%s}xfrm' % DRAWING_NS, ) # no transformation SubElement(frm, '{%s}off' % DRAWING_NS, {'x': '0', 'y': '0'}) SubElement(frm, '{%s}ext' % DRAWING_NS, {'cx': '0', 'cy': '0'}) prstgeom = SubElement(sppr, '{%s}prstGeom' % DRAWING_NS, {'prst': str(shape.style)}) SubElement(prstgeom, '{%s}avLst' % DRAWING_NS) fill = SubElement( sppr, '{%s}solidFill' % DRAWING_NS, ) SubElement(fill, '{%s}srgbClr' % DRAWING_NS, {'val': shape.color}) border = SubElement(sppr, '{%s}ln' % DRAWING_NS, {'w': str(shape._border_width)}) sf = SubElement(border, '{%s}solidFill' % DRAWING_NS) SubElement(sf, '{%s}srgbClr' % DRAWING_NS, {'val': shape.border_color}) self._write_style(sp) self._write_text(sp, shape) shape_id += 1 return tostring(root)
def test_to_tree(self, Dummy): dummy = Dummy([1, '2', 3]) root = Element("root") for node in Dummy.value.to_tree("el", dummy.value, ): root.append(node) xml = tostring(root) expected = """ <root> <el>1</el> <el>2</el> <el>3</el> </root> """ diff = compare_xml(xml, expected) assert diff is None, diff
def test_namespace_register(): from openpyxl2.xml.functions import Element, tostring from openpyxl2.xml.constants import SHEET_MAIN_NS e = Element('{%s}sheet' % SHEET_MAIN_NS) xml = tostring(e) if hasattr(xml, "decode"): xml = xml.decode("utf-8") assert xml.startswith("<s:sheet")
def to_tree(self): def sorter(value): value.reindex() return value.min el = Element('cols') obj = None outlines = set() for col in sorted(self.values(), key=sorter): obj = col.to_tree() outlines.add(col.outlineLevel) if obj is not None: el.append(obj) if outlines: self.max_outline = max(outlines) if obj is not None: return el
def test_to_tree(self, Stooge): dummy = Stooge() dummy._stooges = [Larry(1), Curly(2), Larry(3), Mo(4)] root = Element("root") for node in Stooge._stooges.to_tree("el", dummy._stooges): root.append(node) tree = dummy.to_tree("root") xml = tostring(root) expected = """ <root> <l value="1"></l> <c hair="2"></c> <l value="3"></l> <m cap="4"></m> </root> """ diff = compare_xml(xml, expected) assert diff is None, diff
def to_tree(self, tagname, obj, namespace=None): tagname = namespaced(self, tagname, namespace) container = Element(tagname) if self.count: container.set('count', str(len(obj))) for v in obj: container.append(v.to_tree()) return container
def test_to_tree(self, Sequence): class Dummy: vals = Sequence(expected_type=SomeType, name="vals") dummy = Dummy() dummy.vals = [SomeType(1), SomeType(2), SomeType(3)] root = Element("root") for node in Dummy.vals.to_tree("el", dummy.vals): root.append(node) xml = tostring(root) expected = """ <root> <el value="1"></el> <el value="2"></el> <el value="3"></el> </root> """ diff = compare_xml(xml, expected) assert diff is None, diff
def to_tree(self, tagname=None, idx=None, namespace=None): if tagname is None: tagname = self.tagname # keywords have to be masked if tagname.startswith("_"): tagname = tagname[1:] tagname = namespaced(self, tagname, namespace) namespace = getattr(self, "namespace", namespace) attrs = dict(self) for key, ns in self.__namespaced__: if key in attrs: attrs[ns] = attrs[key] del attrs[key] el = Element(tagname, attrs) if "attr_text" in self.__attrs__: el.text = safe_string(getattr(self, "attr_text")) for child_tag in self.__elements__: desc = getattr(self.__class__, child_tag, None) obj = getattr(self, child_tag) if isinstance(obj, seq_types): if isinstance(desc, NestedSequence): # wrap sequence in container if not obj: continue nodes = [desc.to_tree(child_tag, obj, namespace)] elif isinstance(desc, Sequence): # sequence desc.idx_base = self.idx_base nodes = (desc.to_tree(child_tag, obj, namespace)) else: # property nodes = (v.to_tree(child_tag, namespace) for v in obj) for node in nodes: el.append(node) else: if child_tag in self.__nested__: node = desc.to_tree(child_tag, obj, namespace) elif obj is None: continue else: node = obj.to_tree(child_tag) if node is not None: el.append(node) return el
def write_string_table(string_table): """Write the string table xml.""" out = BytesIO() with xmlfile(out) as xf: with xf.element("sst", xmlns=SHEET_MAIN_NS, uniqueCount="%d" % len(string_table)): for key in string_table: el = Element('si') text = SubElement(el, 't') text.text = key if key.strip() != key: text.set(PRESERVE_SPACE, 'preserve') xf.write(el) return out.getvalue()
def etree_write_cell(xf, worksheet, cell, styled=None): coordinate = cell.coordinate attributes = {'r': coordinate} if styled: attributes['s'] = '%d' % cell.style_id if cell.data_type != 'f': attributes['t'] = cell.data_type value = cell._value if cell.data_type == "d": if cell.parent.parent.iso_dates: if isinstance(value, timedelta): value = days_to_time(value) value = value.isoformat() else: attributes['t'] = "n" value = to_excel(value, worksheet.parent.epoch) if cell._comment is not None: comment = CommentRecord.from_cell(cell) worksheet._comments.append(comment) el = Element("c", attributes) if value is None or value == "": xf.write(el) return if cell.data_type == 'f': shared_formula = worksheet.formula_attributes.get(coordinate, {}) formula = SubElement(el, 'f', shared_formula) if value is not None: formula.text = value[1:] value = None if cell.data_type == 's': value = worksheet.parent.shared_strings.add(value) cell_content = SubElement(el, 'v') if value is not None: cell_content.text = safe_string(value) if cell.hyperlink: worksheet._hyperlinks.append(cell.hyperlink) xf.write(el)
def test_write_comments_vml(datadir): datadir.chdir() cw = ShapeWriter(create_comments()) content = cw.write(Element("xml")) with open('commentsDrawing1.vml', 'rb') as expected: correct = fromstring(expected.read()) check = fromstring(content) correct_ids = [] correct_coords = [] check_ids = [] check_coords = [] for i in correct.findall("{%s}shape" % vmlns): correct_ids.append(i.attrib["id"]) row = i.find("{%s}ClientData" % excelns).find("{%s}Row" % excelns).text col = i.find("{%s}ClientData" % excelns).find("{%s}Column" % excelns).text correct_coords.append((row, col)) # blank the data we are checking separately i.attrib["id"] = "0" i.find("{%s}ClientData" % excelns).find("{%s}Row" % excelns).text = "0" i.find("{%s}ClientData" % excelns).find("{%s}Column" % excelns).text = "0" for i in check.findall("{%s}shape" % vmlns): check_ids.append(i.attrib["id"]) row = i.find("{%s}ClientData" % excelns).find("{%s}Row" % excelns).text col = i.find("{%s}ClientData" % excelns).find("{%s}Column" % excelns).text check_coords.append((row, col)) # blank the data we are checking separately i.attrib["id"] = "0" i.find("{%s}ClientData" % excelns).find("{%s}Row" % excelns).text = "0" i.find("{%s}ClientData" % excelns).find("{%s}Column" % excelns).text = "0" assert set(correct_coords) == set(check_coords) assert set(correct_ids) == set(check_ids) diff = compare_xml(tostring(correct), tostring(check)) assert diff is None, diff
def write(self, root): if not hasattr(root, "findall"): root = Element("xml") # Remove any existing comment shapes comments = root.findall("{%s}shape[@type='#_x0000_t202']" % vmlns) for c in comments: root.remove(c) # check whether comments shape type already exists shape_types = root.find("{%s}shapetype[@id='_x0000_t202']" % vmlns) if not shape_types: self.add_comment_shapetype(root) for idx, (coord, comment) in enumerate(self.comments, 1026): self.add_comment_shape(root, idx, coord, comment.height, comment.width) return tostring(root)
def to_tree(self, tagname, obj, namespace=None): tagname = namespaced(self, tagname, namespace) for v in obj: yield Element(tagname, {self.attribute:safe_string(v)})
def _no_value(tagname, value, namespace=None): if value: return Element(tagname, val=safe_string(value))
def to_tree(self, tagname=None, namespace=None, idx=None): parent = Element("fill") el = super(GradientFill, self).to_tree() parent.append(el) return parent
def to_tree(self): attrs = dict(self) return Element("col", **attrs)