예제 #1
0
    def _writer(doc):
        with xmlfile(doc) as xf:
            with xf.element('sheetData'):
                try:
                    while True:
                        row = (yield)
                        with xf.element("row"):
                            for cell in row:
                                with xf.element("v"):
                                    xf.write(str(cell))

                except GeneratorExit:
                    pass
예제 #2
0
def test_write_comment(worksheet, write_cell_implementation):

    write_cell = write_cell_implementation
    from openpyxl2.comments import Comment

    ws = worksheet
    cell = ws['A1']
    cell.comment = Comment("test comment", "test author")

    out = BytesIO()
    with xmlfile(out) as xf:
        write_cell(xf, ws, cell, False)
    assert len(ws._comments) == 1
예제 #3
0
def test_write_cell(worksheet, write_cell_implementation, value, expected):
    write_cell = write_cell_implementation

    ws = worksheet
    cell = ws['A1']
    cell.value = value

    out = BytesIO()
    with xmlfile(out) as xf:
        write_cell(xf, ws, cell, cell.has_style)

    xml = out.getvalue()
    diff = compare_xml(xml, expected)
    assert diff is None, diff
예제 #4
0
파일: strings.py 프로젝트: j5int/openpyxl2
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()
예제 #5
0
def test_write_formula(worksheet, write_rows):
    ws = worksheet

    ws['F1'] = 10
    ws['F2'] = 32
    ws['F3'] = '=F1+F2'
    ws['A4'] = '=A1+A2+A3'
    ws['B4'] = "=SUM(A10:A14*B10:B14)"
    ws.formula_attributes['B4'] = {'t': 'array', 'ref': 'B4:B8'}

    out = BytesIO()
    with xmlfile(out) as xf:
        write_rows(xf, ws)

    xml = out.getvalue()
    expected = """
    <sheetData>
      <row r="1" spans="1:6">
        <c r="F1" t="n">
          <v>10</v>
        </c>
      </row>
      <row r="2" spans="1:6">
        <c r="F2" t="n">
          <v>32</v>
        </c>
      </row>
      <row r="3" spans="1:6">
        <c r="F3">
          <f>F1+F2</f>
          <v></v>
        </c>
      </row>
      <row r="4" spans="1:6">
        <c r="A4">
          <f>A1+A2+A3</f>
          <v></v>
        </c>
        <c r="B4">
          <f ref="B4:B8" t="array">SUM(A10:A14*B10:B14)</f>
          <v></v>
        </c>
      </row>
    </sheetData>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
예제 #6
0
def test_write_height(worksheet, write_rows):
    from openpyxl2.worksheet.dimensions import RowDimension
    ws = worksheet
    ws['F1'] = 10

    ws.row_dimensions[1] = RowDimension(ws, height=30)
    ws.row_dimensions[2] = RowDimension(ws, height=30)

    out = BytesIO()
    with xmlfile(out) as xf:
        write_rows(xf, ws)
    xml = out.getvalue()
    expected = """
     <sheetData>
       <row customHeight="1" ht="30" r="1" spans="1:6">
         <c r="F1" t="n">
           <v>10</v>
         </c>
       </row>
       <row customHeight="1" ht="30" r="2" spans="1:6"></row>
     </sheetData>
    """
    diff = compare_xml(xml, expected)
    assert diff is None, diff
예제 #7
0
    def _write_header(self):
        """
        Generator that creates the XML file and the sheet header
        """

        with xmlfile(self.filename) as xf:
            with xf.element("worksheet", xmlns=SHEET_MAIN_NS):

                if self.sheet_properties:
                    pr = self.sheet_properties.to_tree()

                xf.write(pr)
                xf.write(self.views.to_tree())

                cols = self.column_dimensions.to_tree()

                self.sheet_format.outlineLevelCol = self.column_dimensions.max_outline
                xf.write(self.sheet_format.to_tree())

                if cols is not None:
                    xf.write(cols)

                with xf.element("sheetData"):
                    cell = WriteOnlyCell(self)
                    try:
                        while True:
                            row = (yield)
                            row_idx = self._max_row
                            attrs = {'r': '%d' % row_idx}
                            if row_idx in self.row_dimensions:
                                dim = self.row_dimensions[row_idx]
                                attrs.update(dict(dim))

                            with xf.element("row", attrs):

                                for col_idx, value in enumerate(row, 1):
                                    if value is None:
                                        continue
                                    try:
                                        cell.value = value
                                    except ValueError:
                                        if isinstance(value, Cell):
                                            cell = value
                                        else:
                                            raise ValueError

                                    cell.col_idx = col_idx
                                    cell.row = row_idx

                                    styled = cell.has_style
                                    write_cell(xf, self, cell, styled)

                                    if styled:  # styled cell or datetime
                                        cell = WriteOnlyCell(self)

                    except GeneratorExit:
                        pass

                if self.protection.sheet:
                    xf.write(self.protection.to_tree())

                if self.auto_filter.ref:
                    xf.write(self.auto_filter.to_tree())

                if self.sort_state.ref:
                    xf.write(self.sort_state.to_tree())

                if self.conditional_formatting:
                    cfs = write_conditional_formatting(self)
                    for cf in cfs:
                        xf.write(cf)

                if self.data_validations.count:
                    xf.write(self.data_validations.to_tree())

                if bool(self.HeaderFooter):
                    xf.write(self.HeaderFooter.to_tree())

                drawing = write_drawing(self)
                if drawing is not None:
                    xf.write(drawing)

                if self._comments:
                    legacyDrawing = Related(id="anysvml")
                    xml = legacyDrawing.to_tree("legacyDrawing")
                    xf.write(xml)
예제 #8
0
def write_worksheet(worksheet):
    """Write a worksheet to an xml file."""

    ws = worksheet
    ws._rels = RelationshipList()
    ws._hyperlinks = []

    out = BytesIO()

    with xmlfile(out) as xf:
        with xf.element('worksheet', xmlns=SHEET_MAIN_NS):

            props = ws.sheet_properties.to_tree()
            xf.write(props)

            dim = SheetDimension(ref=ws.calculate_dimension())
            xf.write(dim.to_tree())

            xf.write(ws.views.to_tree())

            cols = ws.column_dimensions.to_tree()
            ws.sheet_format.outlineLevelCol = ws.column_dimensions.max_outline
            xf.write(ws.sheet_format.to_tree())

            if cols is not None:
                xf.write(cols)

            # write data
            write_rows(xf, ws)

            if ws.protection:
                xf.write(ws.protection.to_tree())

            if ws.auto_filter:
                xf.write(ws.auto_filter.to_tree())

            if ws.sort_state:
                xf.write(ws.sort_state.to_tree())

            merge = write_mergecells(ws)
            if merge is not None:
                xf.write(merge)

            cfs = write_conditional_formatting(ws)
            for cf in cfs:
                xf.write(cf)

            if ws.data_validations:
                xf.write(ws.data_validations.to_tree())

            hyper = write_hyperlinks(ws)
            if hyper:
                xf.write(hyper.to_tree())

            options = ws.print_options
            if dict(options):
                new_element = options.to_tree()
                xf.write(new_element)

            margins = ws.page_margins.to_tree()
            xf.write(margins)

            setup = ws.page_setup
            if dict(setup):
                new_element = setup.to_tree()
                xf.write(new_element)

            if bool(ws.HeaderFooter):
                xf.write(ws.HeaderFooter.to_tree())

            if ws.page_breaks:
                xf.write(ws.page_breaks.to_tree())

            drawing = write_drawing(ws)
            if drawing is not None:
                xf.write(drawing)

            # if there is an existing vml file associated with this sheet or if there
            # are any comments we need to add a legacyDrawing relation to the vml file.
            if (ws.legacy_drawing is not None or ws._comments):
                legacyDrawing = Related(id="anysvml")
                xml = legacyDrawing.to_tree("legacyDrawing")
                xf.write(xml)

            tables = _add_table_headers(ws)
            if tables:
                xf.write(tables.to_tree())

    xml = out.getvalue()
    out.close()
    return xml