def start_tag(doc, name, attr=None, body=None, namespace=None):
    """Wrapper to start an xml tag."""
    if attr is None:
        attr = OrderedDict()

    attr_vals = OrderedDict()
    attr_keys = OrderedDict()
    for key, val in attr.items():
        key_tuple = (namespace, key)
        attr_vals[key_tuple] = val
        attr_keys[key_tuple] = key
    attr2 = AttributesNSImpl(attr_vals, attr_keys)
    doc.startElementNS((namespace, name), name, attr2)
    if body:
        doc.characters(body)
def collapse_cell_addresses(cells, input_ranges=()):
    """ Collapse a collection of cell co-ordinates down into an optimal
        range or collection of ranges.

        E.g. Cells A1, A2, A3, B1, B2 and B3 should have the data-validation
        object applied, attempt to collapse down to a single range, A1:B3.

        Currently only collapsing contiguous vertical ranges (i.e. above
        example results in A1:A3 B1:B3).  More work to come.
    """
    keyfunc = lambda x: x[0]

    # Get the raw coordinates for each cell given
    raw_coords = [coordinate_from_string(cell) for cell in cells]

    # Group up as {column: [list of rows]}
    grouped_coords = OrderedDict((k, [c[1] for c in g]) for k, g in
                          groupby(sorted(raw_coords, key=keyfunc), keyfunc))
    ranges = list(input_ranges)

    # For each column, find contiguous ranges of rows
    for column in grouped_coords:
        rows = sorted(grouped_coords[column])
        grouped_rows = [[r[1] for r in list(g)] for k, g in
                        groupby(enumerate(rows),
                        lambda x: x[0] - x[1])]
        for rows in grouped_rows:
            if len(rows) == 0:
                pass
            elif len(rows) == 1:
                ranges.append("%s%d" % (column, rows[0]))
            else:
                ranges.append("%s%d:%s%d" % (column, rows[0], column, rows[-1]))

    return " ".join(ranges)
Exemple #3
0
    def margins(self):
        margins = OrderedDict()
        for margin_name in self.valid_margins:
            margin_value = getattr(self, margin_name)
            if margin_value:
                margins[margin_name] = "%0.2f" % margin_value

        return margins
Exemple #4
0
    def options(self):
        optionsGroup = OrderedDict()
        for options_name in self.valid_options:
            options_value = getattr(self, options_name)
            if options_value is not None:
                optionsGroup[options_name] = '1'

        return optionsGroup
Exemple #5
0
    def options(self):
        optionsGroup = OrderedDict()
        for options_name in self.valid_options:
            options_value = getattr(self, options_name)
            if options_value is not None:
                if options_name in ('horizontalCentered',
                                    'verticalCentered') and options_value:
                    optionsGroup[options_name] = '1'

        return optionsGroup
Exemple #6
0
    def setup(self):
        setupGroup = OrderedDict()
        for setup_name in self.valid_setup:
            setup_value = getattr(self, setup_name)
            if setup_value is not None:
                if setup_name == 'orientation':
                    setupGroup[setup_name] = '%s' % setup_value
                elif setup_name in ('paperSize', 'scale'):
                    setupGroup[setup_name] = '%d' % int(setup_value)
                elif setup_name in ('fitToHeight',
                                    'fitToWidth') and int(setup_value) >= 0:
                    setupGroup[setup_name] = '%d' % int(setup_value)

        return setupGroup
Exemple #7
0
 def __init__(self, parent_workbook, title='Sheet'):
     self._parent = parent_workbook
     self._title = ''
     if not title:
         self.title = 'Sheet%d' % (1 + len(self._parent.worksheets))
     else:
         self.title = title
     self.row_dimensions = {}
     self.column_dimensions = OrderedDict([])
     self.page_breaks = []
     self._cells = {}
     self._styles = {}
     self._charts = []
     self._images = []
     self._comment_count = 0
     self._merged_cells = []
     self.relationships = []
     self._data_validations = []
     self.selected_cell = 'A1'
     self.active_cell = 'A1'
     self.sheet_state = self.SHEETSTATE_VISIBLE
     self.page_setup = PageSetup()
     self.page_margins = PageMargins()
     self.header_footer = HeaderFooter()
     self.sheet_view = SheetView()
     self.protection = SheetProtection()
     self.show_gridlines = True
     self.print_gridlines = False
     self.show_summary_below = True
     self.show_summary_right = True
     self.default_row_dimension = RowDimension()
     self.default_column_dimension = ColumnDimension()
     self._auto_filter = None
     self._freeze_panes = None
     self.paper_size = None
     self.formula_attributes = {}
     self.orientation = None
     self.xml_source = None
     self.conditional_formatting = ConditionalFormatting()
 def __init__(self):
     self.cf_rules = OrderedDict()
     self.max_priority = 0
Exemple #9
0
    'numeric': {
        'type': Cell.TYPE_NUMERIC,
        'style': '0'
    },
    'formula': {
        'type': Cell.TYPE_FORMULA,
        'style': '0'
    },
    'boolean': {
        'type': Cell.TYPE_BOOL,
        'style': '0'
    },
}

DESCRIPTORS_CACHE_SIZE = 50
DESCRIPTORS_CACHE = OrderedDict()

DATETIME_STYLE = Style()
DATETIME_STYLE.number_format.format_code = 'yyyy-mm-dd h:mm'

DATE_STYLE = Style()
DATE_STYLE.number_format.format_code = 'yyyy-mm-dd'

BOUNDING_BOX_PLACEHOLDER = 'A1:%s%d' % (get_column_letter(MAX_COLUMN), MAX_ROW)


def create_temporary_file(suffix=''):

    fobj = NamedTemporaryFile(mode='w+',
                              suffix=suffix,
                              prefix='openpyxl.',
 def _descriptors_cache(self):
     try:
         return self._parent._local_data.cache
     except AttributeError:
         self._parent._local_data.cache = OrderedDict()
         return self._parent._local_data.cache