Exemple #1
0
    def write_data(self):
        """Write the various xml files into the zip archive."""
        # cleanup all worksheets
        archive = self._archive

        archive.writestr(ARC_ROOT_RELS, write_root_rels(self.workbook))
        props = ExtendedProperties()
        archive.writestr(ARC_APP, tostring(props.to_tree()))

        archive.writestr(ARC_CORE,
                         tostring(self.workbook.properties.to_tree()))
        if self.workbook.loaded_theme:
            archive.writestr(ARC_THEME, self.workbook.loaded_theme)
        else:
            archive.writestr(ARC_THEME, write_theme())

        self._write_worksheets()
        self._write_chartsheets()
        self._write_images()
        self._write_charts()

        self._archive.writestr(
            ARC_SHARED_STRINGS,
            write_string_table(self.workbook.shared_strings))
        self._write_external_links()

        stylesheet = write_stylesheet(self.workbook)
        archive.writestr(ARC_STYLE, tostring(stylesheet))

        archive.writestr(ARC_WORKBOOK, write_workbook(self.workbook))
        archive.writestr(ARC_WORKBOOK_RELS, write_workbook_rels(self.workbook))

        self._merge_vba()

        self.manifest._write(archive, self.workbook)
Exemple #2
0
    def _write_external_links(self):
        # delegate to object
        """Write links to external workbooks"""
        wb = self.workbook
        for idx, link in enumerate(wb._external_links, 1):
            link._id = idx
            rels_path = get_rels_path(link.path[1:])

            xml = link.to_tree()
            self._archive.writestr(link.path[1:], tostring(xml))
            rels = RelationshipList()
            rels.append(link.file_link)
            self._archive.writestr(rels_path, tostring(rels.to_tree()))
            self.manifest.append(link)
Exemple #3
0
 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
Exemple #4
0
 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
Exemple #5
0
    def test_ctor(self, ComplexObject):
        style = ComplexObject()
        ft1 = Font(family=2, sz=11, name="Arial")
        ft2 = Font(bold=True)
        style.fonts = [ft1, ft2]

        expected = """
        <style>
          <fonts count="2">
            <font>
              <name val="Arial" />
              <family val="2"></family>
              <sz val="11"></sz>
            </font>
            <font>
              <b val="1"></b>
            </font>
          </fonts>
        </style>
        """
        tree = style.__class__.fonts.to_tree('fonts', style.fonts)
        tree = style.to_tree()
        xml = tostring(tree)
        diff = compare_xml(xml, expected)

        assert diff is None, diff
    def test_conditional_formatting_customRule(self):

        worksheet = self.ws
        worksheet.conditional_formatting.add(
            'C1:C10',
            Rule(
                **{
                    'type': 'expression',
                    'formula': ['ISBLANK(C1)'],
                    'stopIfTrue': '1',
                }))
        cfs = write_conditional_formatting(worksheet)
        xml = b""
        for cf in cfs:
            xml += tostring(cf)

        diff = compare_xml(
            xml, """
        <conditionalFormatting sqref="C1:C10">
          <cfRule type="expression" stopIfTrue="1" priority="1">
            <formula>ISBLANK(C1)</formula>
          </cfRule>
        </conditionalFormatting>
        """)
        assert diff is None, diff
Exemple #7
0
 def test_ctor(self, ManualLayout):
     layout = ManualLayout(
         layoutTarget="inner",
         xMode="edge",
         yMode="factor",
         wMode="factor",
         hMode="edge",
         x=10,
         y=50,
         w=4,
         h=100
     )
     xml = tostring(layout.to_tree())
     expected = """
     <manualLayout>
       <layoutTarget val="inner"></layoutTarget>
       <xMode val="edge"></xMode>
       <yMode val="factor"></yMode>
       <wMode val="factor"></wMode>
       <hMode val="edge"></hMode>
       <x val="10"></x>
       <y val="50"></y>
       <w val="4"></w>
       <h val="100"></h>
     </manualLayout>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #8
0
 def test_ctor(self, SortCondition):
     cond = SortCondition(ref='A2:A3', descending=True)
     expected = """
     <sortCondtion descending="1" ref="A2:A3"></sortCondtion>
     """
     xml = tostring(cond.to_tree())
     diff = compare_xml(xml, expected)
Exemple #9
0
 def _write(self, archive, manifest):
     """
     Write to zipfile and update manifest
     """
     xml = tostring(self.to_tree())
     archive.writestr(self.path[1:], xml)
     manifest.append(self)
Exemple #10
0
 def test_zvalues(self, Series):
     series = Series("Sheet!A2:A5",
                     xvalues="Sheet!B2:B5",
                     zvalues="Sheet!C2:C5")
     series.__elements__ = ('xVal', 'yVal', 'bubbleSize')
     xml = tostring(series.to_tree())
     expected = """
     <ser>
       <xVal>
         <numRef>
           <f>'Sheet'!$B$2:$B$5</f>
         </numRef>
       </xVal>
       <yVal>
         <numRef>
           <f>'Sheet'!$A$2:$A$5</f>
         </numRef>
       </yVal>
       <bubbleSize>
         <numRef>
           <f>'Sheet'!$C$2:$C$5</f>
         </numRef>
       </bubbleSize>
     </ser>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
 def test_empty_dv(self, DataValidationList, DataValidation):
     dv = DataValidation()
     dvs = DataValidationList(dataValidation=[dv])
     xml = tostring(dvs.to_tree())
     expected = '<dataValidations count="0"/>'
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #12
0
 def test_serialise(self, Border, Side):
     medium_blue = Side(border_style='medium', color=Color(colors.BLUE))
     bd = Border(
         left=medium_blue,
         right=medium_blue,
         top=medium_blue,
         bottom=medium_blue,
         outline=False,
         diagonalDown=True,
     )
     xml = tostring(bd.to_tree())
     expected = """
     <border diagonalDown="1" outline="0">
       <left style="medium">
         <color rgb="000000FF"></color>
       </left>
       <right style="medium">
         <color rgb="000000FF"></color>
       </right>
       <top style="medium">
         <color rgb="000000FF"></color>
        </top>
       <bottom style="medium">
          <color rgb="000000FF"></color>
        </bottom>
        <diagonal />
     </border>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #13
0
 def test_from_xml(self, PictureFrame):
     src = """
     <pic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
     <nvPicPr>
         <cNvPr descr="Picture" id="1" name="Image 1"/>
         <cNvPicPr/>
     </nvPicPr>
     <blipFill>
         <a:blip xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" cstate="print" r:embed="rId1"/>
         <a:stretch>
             <a:fillRect/>
         </a:stretch>
     </blipFill>
     <spPr>
         <a:xfrm>
             <a:off x="303" y="0"/>
             <a:ext cx="321" cy="88"/>
         </a:xfrm>
         <a:prstGeom prst="rect"/>
         <a:ln>
           <a:prstDash val="solid" />
         </a:ln>
     </spPr>
     </pic>
     """
     node = fromstring(src)
     graphic = PictureFrame.from_tree(node)
     xml = tostring(graphic.to_tree())
     diff = compare_xml(xml, src)
     assert diff is None, diff
Exemple #14
0
    def test_from_tree(self):
        from ..series import Series, attribute_mapping

        src = """
        <ser>
          <idx val="0"/>
          <order val="0"/>
          <spPr>
              <a:ln xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
                <a:prstDash val="solid" />
              </a:ln>
            </spPr>
          <val>
            <numRef>
              <f>Blatt1!$A$1:$A$12</f>
            </numRef>
          </val>
        </ser>
        """
        node = fromstring(src)
        ser = Series.from_tree(node)
        assert ser.idx == 0
        assert ser.order == 0
        assert ser.val.numRef.ref == 'Blatt1!$A$1:$A$12'

        ser.__elements__ = attribute_mapping['area']
        xml = tostring(ser.to_tree())
        diff = compare_xml(xml, src)
        assert diff is None, diff
Exemple #15
0
def test_simple_styles(datadir):
    import datetime
    from openpyexcel import Workbook
    from ..protection import Protection
    from .. import numbers
    from ..stylesheet import write_stylesheet
    wb = Workbook()
    wb.guess_types = True
    ws = wb.active
    now = datetime.date.today()
    for idx, v in enumerate(
        ['12.34%', now, 'This is a test', '31.31415', None], 1):
        ws.append([v])
        _ = ws.cell(column=1, row=idx).style_id

    # set explicit formats
    ws['D9'].number_format = numbers.FORMAT_NUMBER_00
    ws['D9'].protection = Protection(locked=True)
    ws['D9'].style_id
    ws['E1'].protection = Protection(hidden=True)
    ws['E1'].style_id

    assert len(wb._cell_styles) == 5
    stylesheet = write_stylesheet(wb)

    datadir.chdir()
    with open('simple-styles.xml') as reference_file:
        expected = reference_file.read()
    xml = tostring(stylesheet)
    diff = compare_xml(xml, expected)
    assert diff is None, diff
Exemple #16
0
def test_conditional_font(worksheet_with_cf, write_conditional_formatting):
    """Test to verify font style written correctly."""

    # Create cf rule
    from openpyexcel.styles import PatternFill, Font, Color
    from openpyexcel.formatting.rule import CellIsRule

    redFill = PatternFill(start_color=Color('FFEE1111'),
                          end_color=Color('FFEE1111'),
                          patternType='solid')
    whiteFont = Font(color=Color("FFFFFFFF"))

    ws = worksheet_with_cf
    ws.conditional_formatting.add(
        'A1:A3',
        CellIsRule(operator='equal',
                   formula=['"Fail"'],
                   stopIfTrue=False,
                   font=whiteFont,
                   fill=redFill))
    cfs = write_conditional_formatting(ws)
    xml = b""
    for cf in cfs:
        xml += tostring(cf)
    diff = compare_xml(
        xml, """
    <conditionalFormatting sqref="A1:A3">
      <cfRule operator="equal" priority="1" type="cellIs" dxfId="0" stopIfTrue="0">
        <formula>"Fail"</formula>
      </cfRule>
    </conditionalFormatting>
    """)
    assert diff is None, diff
Exemple #17
0
def test_title_maker():
    """
    Create a title element from a string preserving line breaks.
    """

    from ..title import title_maker
    text = "Two-line\nText"
    title = title_maker(text)
    xml = tostring(title.to_tree())
    expected = """
    <title xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
          <tx>
            <rich>
              <a:bodyPr />
              <a:p>
                <a:r>
                  <a:t>Two-line</a:t>
                </a:r>
              </a:p>
              <a:p>
                <a:r>
                  <a:t>Text</a:t>
                </a:r>
              </a:p>
            </rich>
          </tx>
    </title>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
Exemple #18
0
 def test_ctor(self, MergeCell):
     cell = MergeCell("A1")
     node = cell.to_tree()
     xml = tostring(node)
     expected = "<mergeCell ref='A1' />"
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #19
0
 def _write_drawing(self, drawing):
     """
     Write a drawing
     """
     self._drawings.append(drawing)
     drawing._id = len(self._drawings)
     for chart in drawing.charts:
         self._charts.append(chart)
         chart._id = len(self._charts)
     for img in drawing.images:
         self._images.append(img)
         img._id = len(self._images)
     rels_path = get_rels_path(drawing.path)[1:]
     self._archive.writestr(drawing.path[1:], tostring(drawing._write()))
     self._archive.writestr(rels_path, tostring(drawing._write_rels()))
     self.manifest.append(drawing)
Exemple #20
0
def test_ctor(SampleProperties):
    expected = """
    <coreProperties
        xmlns="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
        xmlns:dc="http://purl.org/dc/elements/1.1/"
        xmlns:dcterms="http://purl.org/dc/terms/"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <dc:creator>TEST_USER</dc:creator>
        <dc:title>The title</dc:title>
        <dc:description>The description</dc:description>
        <dc:subject>The subject</dc:subject>
        <dc:identifier>The identifier</dc:identifier>
        <dc:language>The language</dc:language>
        <dcterms:created xsi:type="dcterms:W3CDTF">2010-04-01T20:30:00Z</dcterms:created>
        <dcterms:modified xsi:type="dcterms:W3CDTF">2010-04-05T14:05:30Z</dcterms:modified>
        <lastModifiedBy>SOMEBODY</lastModifiedBy>
        <category>The category</category>
        <contentStatus>The status</contentStatus>
        <version>2.5</version>
        <revision>0</revision>
        <keywords>one, two, three</keywords>
        <lastPrinted>2014-10-14T10:30:00Z</lastPrinted>
    </coreProperties>
    """
    xml = tostring(SampleProperties.to_tree())
    diff = compare_xml(xml, expected)
    assert diff is None, diff
Exemple #21
0
 def test_ctor(self, BookView):
     view = BookView()
     xml = tostring(view.to_tree())
     expected = """
     <workbookView activeTab="0" autoFilterDateGrouping="1" firstSheet="0" minimized="0" showHorizontalScroll="1" showSheetTabs="1" showVerticalScroll="1" tabRatio="600" visibility="visible"/>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #22
0
 def test_ctor(self, NonVisualGraphicFrameProperties):
     graphic = NonVisualGraphicFrameProperties()
     xml = tostring(graphic.to_tree())
     expected = """
     <cNvGraphicFramePr></cNvGraphicFramePr>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #23
0
 def test_ctor(self, GraphicData):
     graphic = GraphicData()
     xml = tostring(graphic.to_tree())
     expected = """
     <graphicData xmlns="http://schemas.openxmlformats.org/drawingml/2006/main" uri="http://schemas.openxmlformats.org/drawingml/2006/chart" />
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #24
0
 def test_ctor(self, GroupTransform2D):
     xfrm = GroupTransform2D(rot=0)
     xml = tostring(xfrm.to_tree())
     expected = """
     <xfrm rot="0" xmlns="http://schemas.openxmlformats.org/drawingml/2006/main"></xfrm>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #25
0
 def test_ctor(self, GroupShape):
     grp = GroupShape()
     xml = tostring(grp.to_tree())
     expected = """
     <root />
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #26
0
 def test_ctor(self, ParagraphProperties):
     text = ParagraphProperties()
     xml = tostring(text.to_tree())
     expected = """
     <pPr xmlns="http://schemas.openxmlformats.org/drawingml/2006/main" />
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #27
0
 def test_ctor(self, Hyperlink):
     link = Hyperlink()
     xml = tostring(link.to_tree())
     expected = """
     <hlinkClick xmlns="http://schemas.openxmlformats.org/drawingml/2006/main"/>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
 def test_ctor(self, BandFormatList):
     fmt = BandFormatList()
     xml = tostring(fmt.to_tree())
     expected = """
     <bandFmts />
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #29
0
 def test_ctor(self, TableStyleElement):
     table = TableStyleElement(type="wholeTable", dxfId=4)
     xml = tostring(table.to_tree())
     expected = """
     <tableStyleElement type="wholeTable" dxfId="4" />
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff
Exemple #30
0
 def test_ctor(self, TableStyleList):
     table = TableStyleList()
     xml = tostring(table.to_tree())
     expected = """
     <tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleLight16"/>
     """
     diff = compare_xml(xml, expected)
     assert diff is None, diff