示例#1
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
示例#2
0
    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
示例#3
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
示例#4
0
def test_append(WriteOnlyWorksheet, _writer, doc):
    ws = WriteOnlyWorksheet

    ws.writer = _writer
    next(ws.writer)

    ws.append([1, "s"])
    ws.append(['2', 3])
    ws.append(i for i in [1, 2])
    ws.writer.close()
    xml = doc.getvalue()
    expected = """
    <sheetData>
      <row>
          <v>1</v>
          <v>s</v>
      </row>
      <row>
          <v>2</v>
          <v>3</v>
      </row>
      <row>
          <v>1</v>
          <v>2</v>
      </row>
    </sheetData>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#5
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)
示例#6
0
def test_write_height(WriteOnlyWorksheet):
    ws = WriteOnlyWorksheet
    ws.row_dimensions[1].height = 10
    ws.append([4])
    ws.close()

    with open(ws.filename) as src:
        xml = src.read()

    expected = """
    <worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetPr>
      <outlinePr summaryRight="1" summaryBelow="1"/>
      <pageSetUpPr/>
    </sheetPr>
    <sheetViews>
      <sheetView workbookViewId="0">
        <selection sqref="A1" activeCell="A1"/>
       </sheetView>
    </sheetViews>
    <sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>
     <sheetData>
       <row customHeight="1" ht="10" r="1">
         <c r="A1" t="n">
           <v>4</v>
         </c>
       </row>
     </sheetData>
    </worksheet>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#7
0
def test_conditional_formatting(WriteOnlyWorksheet):
    from openpyexcel.formatting.rule import CellIsRule
    ws = WriteOnlyWorksheet
    rule = CellIsRule(operator='lessThan', formula=['C$1'], stopIfTrue=True)
    ws.conditional_formatting.add("C1:C10", rule)
    ws.close()

    with open(ws.filename) as src:
        xml = src.read()

    expected = """
    <worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetPr>
      <outlinePr summaryRight="1" summaryBelow="1"/>
      <pageSetUpPr/>
    </sheetPr>
    <sheetViews>
      <sheetView workbookViewId="0">
        <selection sqref="A1" activeCell="A1"/>
       </sheetView>
    </sheetViews>
    <sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>
     <sheetData />
     <conditionalFormatting sqref="C1:C10">
       <cfRule operator="lessThan" priority="1" stopIfTrue="1" type="cellIs">
         <formula>C$1</formula>
       </cfRule>
     </conditionalFormatting>
    </worksheet>"""
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#8
0
def test_print_titles(Unicode_Workbook):
    wb = Unicode_Workbook
    ws = wb.active
    ws.print_title_rows = '1:5'
    xml = write_workbook(wb)

    expected = """
    <workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
    xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <workbookPr/>
    <workbookProtection/>
    <bookViews>
      <workbookView activeTab="0" autoFilterDateGrouping="1" firstSheet="0" minimized="0" showHorizontalScroll="1" showSheetTabs="1" showVerticalScroll="1" tabRatio="600" visibility="visible"/>
    </bookViews>
    <sheets>
      <sheet name="D&#xFC;sseldorf Sheet" sheetId="1" state="visible" r:id="rId1"/>
    </sheets>
    <definedNames>
      <definedName localSheetId="0" name="_xlnm.Print_Titles">'D&#xFC;sseldorf Sheet'!1:5</definedName>
    </definedNames>
    <calcPr calcId="124519" fullCalcOnLoad="1"/>
    </workbook>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#9
0
def test_print_autofilter(Unicode_Workbook):
    wb = Unicode_Workbook
    ws = wb.active
    ws.auto_filter.ref = "A1:A10"
    ws.auto_filter.add_filter_column(0, ["Kiwi", "Apple", "Mango"])

    xml = write_workbook(wb)

    expected = """
    <workbook xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
    xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <workbookPr/>
    <workbookProtection/>
    <bookViews>
      <workbookView activeTab="0" autoFilterDateGrouping="1" firstSheet="0" minimized="0" showHorizontalScroll="1" showSheetTabs="1" showVerticalScroll="1" tabRatio="600" visibility="visible"/>
    </bookViews>
    <sheets>
      <sheet name="D&#xFC;sseldorf Sheet" sheetId="1" state="visible" r:id="rId1"/>
    </sheets>
    <definedNames>
    <definedName localSheetId="0" hidden="1" name="_xlnm._FilterDatabase">'D&#xFC;sseldorf Sheet'!$A$1:$A$10</definedName>
    </definedNames>
    <calcPr calcId="124519" fullCalcOnLoad="1"/>
    </workbook>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#10
0
 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
示例#11
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
示例#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
示例#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
示例#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
示例#15
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
示例#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
示例#17
0
def test_frozen_panes(WriteOnlyWorksheet):
    ws = WriteOnlyWorksheet
    ws.freeze_panes = 'D4'
    ws.close()
    with open(ws.filename) as src:
        xml = src.read()
    expected = """
    <worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetPr>
      <outlinePr summaryRight="1" summaryBelow="1"/>
      <pageSetUpPr/>
    </sheetPr>
    <sheetViews>
      <sheetView workbookViewId="0">
        <pane xSplit="3" ySplit="3" topLeftCell="D4" activePane="bottomRight" state="frozen"/>
        <selection pane="topRight"/>
        <selection pane="bottomLeft"/>
        <selection pane="bottomRight" activeCell="A1" sqref="A1"/>
      </sheetView>
    </sheetViews>
    <sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>
    <sheetData/>
    </worksheet>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#18
0
def test_write_comments(worksheet, write_worksheet):
    ws = worksheet
    worksheet._comments = True
    xml = write_worksheet(ws)
    expected = """
    <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
    xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
      <sheetPr>
        <outlinePr summaryBelow="1" summaryRight="1"/>
        <pageSetUpPr/>
      </sheetPr>
      <dimension ref="A1:A1"/>
      <sheetViews>
        <sheetView workbookViewId="0">
          <selection activeCell="A1" sqref="A1"/>
        </sheetView>
      </sheetViews>
      <sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>
      <sheetData/>
      <pageMargins bottom="1" footer="0.5" header="0.5" left="0.75" right="0.75" top="1"/>
      <legacyDrawing r:id="anysvml"></legacyDrawing>
    </worksheet>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#19
0
def test_data_validations(WriteOnlyWorksheet):
    from openpyexcel.worksheet.datavalidation import DataValidation
    ws = WriteOnlyWorksheet
    dv = DataValidation(sqref="A1")
    ws.data_validations.append(dv)
    ws.close()

    with open(ws.filename) as src:
        xml = src.read()

    expected = """
    <worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetPr>
      <outlinePr summaryRight="1" summaryBelow="1"/>
      <pageSetUpPr/>
    </sheetPr>
    <sheetViews>
      <sheetView workbookViewId="0">
        <selection sqref="A1" activeCell="A1"/>
       </sheetView>
    </sheetViews>
    <sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>
     <sheetData />
     <dataValidations count="1">
       <dataValidation allowBlank="0" showErrorMessage="1" showInputMessage="1" sqref="A1" />
     </dataValidations>
    </worksheet>"""
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#20
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
示例#21
0
def test_odd_headet(WriteOnlyWorksheet):
    ws = WriteOnlyWorksheet
    ws.oddHeader.center.text = "odd header centre"
    ws.close()

    with open(ws.filename) as src:
        xml = src.read()

    expected = """
    <worksheet xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetPr>
      <outlinePr summaryRight="1" summaryBelow="1"/>
      <pageSetUpPr/>
    </sheetPr>
    <sheetViews>
      <sheetView workbookViewId="0">
        <selection sqref="A1" activeCell="A1"/>
       </sheetView>
    </sheetViews>
    <sheetFormatPr baseColWidth="8" defaultRowHeight="15"/>
     <sheetData />
     <headerFooter>
       <oddHeader>&amp;Codd header centre</oddHeader>
       <oddFooter />
       <evenHeader />
       <evenFooter />
       <firstHeader />
       <firstFooter />
     </headerFooter>
    </worksheet>"""
    diff = compare_xml(xml, expected)
    assert diff is None, diff
示例#22
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
示例#23
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
示例#24
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
示例#25
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
示例#26
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
示例#27
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
示例#28
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
示例#29
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
示例#30
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