Exemple #1
0
def test_date_format_on_non_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = datetime.now()
    cell.value = 'testme'
    eq_('testme', cell.value)
Exemple #2
0
def test_date_format_on_non_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = datetime.now()
    cell.value = 'testme'
    eq_('testme', cell.value)
Exemple #3
0
def test_date_format_on_non_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, "A", 1)
    cell.value = datetime.now()
    cell.value = "testme"
    eq_("testme", cell.value)
def test_is_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = datetime.now()
    assert cell.is_date() == True
    cell.value = 'testme'
    assert 'testme' == cell.value
    assert cell.is_date() is False
Exemple #5
0
def test_is_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = datetime.now()
    eq_(cell.is_date(), True)
    cell.value = 'testme'
    eq_('testme', cell.value)
    eq_(cell.is_date(), False)
Exemple #6
0
def test_is_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = datetime.now()
    assert cell.is_date() == True
    cell.value = 'testme'
    assert 'testme' == cell.value
    assert cell.is_date() is False
Exemple #7
0
def test_is_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, "A", 1)
    cell.value = datetime.now()
    eq_(cell.is_date(), True)
    cell.value = "testme"
    eq_("testme", cell.value)
    eq_(cell.is_date(), False)
Exemple #8
0
def test_is_date():
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = datetime.now()
    eq_(cell.is_date(), True)
    cell.value = 'testme'
    eq_('testme', cell.value)
    assert cell.is_date() is False
Exemple #9
0
def set_and_fill_hours_cell(cell: Cell, cell_value: str) -> None:
    if cell_value is not None:
        cell.value = cell_value
    else:
        cell.value = cell_value
    alignment = Alignment(vertical=constants.VERCTICAL_TOP.value,
                          horizontal=constants.CENTER_ALINGMENT.value)
    cell.alignment = alignment
    cell.number_format = constants.HOURS_FORMAT.value
    set_borders_between_columns(cell)
Exemple #10
0
def test_set_get_date():
    today = datetime(2010, 1, 18, 14, 15, 20, 1600)
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = today
    eq_(today, cell.value)
Exemple #11
0
    def parse_cell(self, element):
        value = element.find(self.VALUE_TAG)
        if value is not None:
            value = value.text
        formula = element.find(self.FORMULA_TAG)
        data_type = element.get('t', 'n')
        coordinate = element.get('r')
        style_id = element.get('s')

        # assign formula to cell value unless only the data is desired
        if formula is not None and not self.data_only:
            data_type = 'f'
            if formula.text:
                value = "=" + formula.text
            else:
                value = "="
            formula_type = formula.get('t')
            if formula_type:
                self.ws.formula_attributes[coordinate] = {'t': formula_type}
                si = formula.get('si')  # Shared group index for shared formulas
                if si:
                    self.ws.formula_attributes[coordinate]['si'] = si
                ref = formula.get('ref')  # Range for shared formulas
                if ref:
                    self.ws.formula_attributes[coordinate]['ref'] = ref


        style = {}
        if style_id is not None:
            style_id = int(style_id)
            style = self.styles[style_id]

        column, row = coordinate_from_string(coordinate)
        cell = Cell(self.ws, column, row, **style)
        self.ws._add_cell(cell)

        if value is not None:
            if data_type == 'n':
                value = cell._cast_numeric(value)
            elif data_type == 'b':
                value = bool(int(value))
            elif data_type == 's':
                value = self.shared_strings[int(value)]
            elif data_type == 'str':
                data_type = 's'

        else:
            if data_type == 'inlineStr':
                data_type = 's'
                child = element.find(self.INLINE_STRING)
                if child is None:
                    child = element.find(self.INLINE_RICHTEXT)
                if child is not None:
                    value = child.text

        if self.guess_types or value is None:
            cell.value = value
        else:
            cell._value=value
            cell.data_type=data_type
Exemple #12
0
def test_set_get_date():
    today = datetime(2010, 1, 18, 14, 15, 20, 1600)
    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = today
    eq_(today, cell.value)
Exemple #13
0
def test_time(value, expected):
    wb = Workbook(guess_types=True)
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = value
    assert cell.value == expected
    assert cell.TYPE_NUMERIC == cell.data_type
def test_time(value, expected):
    wb = Workbook(guess_types=True)
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = value
    assert cell.value == expected
    assert cell.TYPE_NUMERIC == cell.data_type
Exemple #15
0
    def parse_cell(self, element):
        value = element.find(self.VALUE_TAG)
        if value is not None:
            value = value.text
        formula = element.find(self.FORMULA_TAG)
        data_type = element.get('t', 'n')
        coordinate = element.get('r')
        style_id = element.get('s')

        # assign formula to cell value unless only the data is desired
        if formula is not None and not self.data_only:
            data_type = 'f'
            if formula.text:
                value = "=" + formula.text
            else:
                value = "="
            formula_type = formula.get('t')
            if formula_type:
                self.ws.formula_attributes[coordinate] = {'t': formula_type}
                si = formula.get(
                    'si')  # Shared group index for shared formulas
                if si:
                    self.ws.formula_attributes[coordinate]['si'] = si
                ref = formula.get('ref')  # Range for shared formulas
                if ref:
                    self.ws.formula_attributes[coordinate]['ref'] = ref

        style = {}
        if style_id is not None:
            style_id = int(style_id)
            style = self.styles[style_id]

        column, row = coordinate_from_string(coordinate)
        cell = Cell(self.ws, column, row, **style)
        self.ws._add_cell(cell)

        if value is not None:
            if data_type == 'n':
                value = cell._cast_numeric(value)
            elif data_type == 'b':
                value = bool(int(value))
            elif data_type == 's':
                value = self.shared_strings[int(value)]
            elif data_type == 'str':
                data_type = 's'

        else:
            if data_type == 'inlineStr':
                data_type = 's'
                child = element.find(self.INLINE_STRING)
                if child is None:
                    child = element.find(self.INLINE_RICHTEXT)
                if child is not None:
                    value = child.text

        if self.guess_types or value is None:
            cell.value = value
        else:
            cell._value = value
            cell.data_type = data_type
Exemple #16
0
def test_timedelta():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = timedelta(days=1, hours=3)
    eq_(cell.value, 1.125)
    eq_(cell.TYPE_NUMERIC, cell.data_type)
Exemple #17
0
def test_timedelta():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = timedelta(days=1, hours=3)
    eq_(cell.value, 1.125)
    eq_(cell.TYPE_NUMERIC, cell.data_type)
def test_timedelta():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = timedelta(days=1, hours=3)
    assert cell.value == 1.125
    assert cell.TYPE_NUMERIC == cell.data_type
Exemple #19
0
    def remove_wrong_whitespaces(self, cell: Cell) -> None:
        """
        Remove trailing and leading whitespaces when cell is string type. It also fixes all duplicated non-standard
        spaces like new line.
        """

        if cell.data_type == "s":
            cell.value = " ".join(cell.value.split())
Exemple #20
0
def test_timedelta():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)
    cell.value = timedelta(days=1, hours=3)
    assert cell.value == 1.125
    assert cell.TYPE_NUMERIC == cell.data_type
 def put_text(cell: Cell, text, font=None, border=None, alignment=None):
     cell.value = text
     if font:
         cell.font = font
     if border:
         cell.border = border
     if alignment:
         cell.alignment = alignment
     return cell
Exemple #22
0
 def put_text(cell: Cell, text, font=None, border=None, alignment=None):
     cell.value = text
     if font:
         cell.font = font
     if border:
         cell.border = border
     if alignment:
         cell.alignment = alignment
     return cell
def test_is_not_date_color_format():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)

    cell.value = -13.5
    cell.style = cell.style.copy(number_format='0.00_);[Red]\(0.00\)')

    assert cell.is_date() is False
Exemple #24
0
def test_is_not_date_color_format():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, "A", 1)

    cell.value = -13.5
    cell.style.number_format.format_code = "0.00_);[Red]\(0.00\)"

    eq_(cell.is_date(), False)
Exemple #25
0
def test_is_not_date_color_format():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)

    cell.value = -13.5
    cell.style.number_format.format_code = '0.00_);[Red]\(0.00\)'

    assert cell.is_date() is False
Exemple #26
0
def test_is_not_date_color_format():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)

    cell.value = -13.5
    cell.style.number_format.format_code = '0.00_);[Red]\(0.00\)'

    eq_(cell.is_date(), False)
Exemple #27
0
def test_is_not_date_color_format():

    wb = Workbook()
    ws = Worksheet(wb)
    cell = Cell(ws, 'A', 1)

    cell.value = -13.5
    cell.style = cell.style.copy(number_format=NumberFormat('0.00_);[Red]\(0.00\)'))

    assert cell.is_date() is False
Exemple #28
0
    def fixes_result_name(self, sheet_title: str, cell: Cell) -> None:
        """
        """

        if sheet_title in TAB_NAMES:
            return

        if cell.column in ['C', 'D']:
            if cell.data_type == "s":
                for wrong, good in COMMON_MISPELLINGS.items():
                    cell.value = cell.value.replace(wrong, good)
    def set_col_widths(self):
        from openpyxl.utils.cell import get_column_letter
        from openpyxl.cell import Cell
        TYPE_STRING = Cell.TYPE_STRING

        for idx, width in sorted(self._col_widths.iteritems()):
            letter = get_column_letter(idx + 1)
            self.sheet.column_dimensions[letter].width = 1 + min(width, 50)
        for row in self._rows:
            values = []
            for val in row:
                if val:
                    value = val.value
                    cell = Cell(self.sheet, column='A', row=1)
                    if isinstance(value, basestring):
                        cell.set_explicit_value(value, data_type=TYPE_STRING)
                    else:
                        cell.value = value
                    cell.style = val.style
                else:
                    cell = val
                values.append(cell)
            self.sheet.append(values)
        self._rows[:] = ()
Exemple #30
0
    def set_col_widths(self):
        from openpyxl.utils.cell import get_column_letter
        from openpyxl.cell import Cell
        TYPE_STRING = Cell.TYPE_STRING

        for idx, width in sorted(self._col_widths.iteritems()):
            letter = get_column_letter(idx + 1)
            self.sheet.column_dimensions[letter].width = 1 + min(width, 50)
        for row in self._rows:
            values = []
            for val in row:
                if val:
                    value = val.value
                    cell = Cell(self.sheet, column='A', row=1)
                    if isinstance(value, basestring):
                        cell.set_explicit_value(value, data_type=TYPE_STRING)
                    else:
                        cell.value = value
                    cell.style = val.style
                else:
                    cell = val
                values.append(cell)
            self.sheet.append(values)
        self._rows[:] = ()
Exemple #31
0
def _fill_xls_cell(subject: Subject, cell: Cell, col_key: str,
                   request: HttpRequest):
    if col_key == 'id':
        cell.value = subject.pk
    elif col_key == 'image':
        image = subject.image
        if image is None:
            cell.value = ''
        else:
            cell.value = path.basename(image.path)
            cell.hyperlink = request.build_absolute_uri(image.url)
    elif col_key == 'created_at':
        cell.value = subject.created_at
    elif col_key == 'pred_sex':
        cell.value = subject.pred_sex
    elif col_key == 'pred_age':
        cell.value = subject.pred_age
    else:
        raise ValueError(f'Invalid column "{col_key}".')
Exemple #32
0
def test_illegal_chacters():
    from openpyxl.exceptions import IllegalCharacterError
    from openpyxl.compat import xrange
    from itertools import chain
    ws = build_dummy_worksheet()
    cell = Cell(ws, 'A', 1)

    # The bytes 0x00 through 0x1F inclusive must be manually escaped in values.

    illegal_chrs = chain(xrange(9), xrange(11, 13), xrange(14, 32))
    for i in illegal_chrs:
        with pytest.raises(IllegalCharacterError):
            cell.value = chr(i)

        with pytest.raises(IllegalCharacterError):
            cell.value = "A {0} B".format(chr(i))

    cell.value = chr(33)
    cell.value = chr(9)  # Tab
    cell.value = chr(10)  # Newline
    cell.value = chr(13)  # Carriage return
    cell.value = " Leading and trailing spaces are legal "
def test_illegal_chacters():
    from openpyxl.exceptions import IllegalCharacterError
    from openpyxl.compat import range
    from itertools import chain
    ws = build_dummy_worksheet()
    cell = Cell(ws, 'A', 1)

    # The bytes 0x00 through 0x1F inclusive must be manually escaped in values.

    illegal_chrs = chain(range(9), range(11, 13), range(14, 32))
    for i in illegal_chrs:
        with pytest.raises(IllegalCharacterError):
            cell.value = chr(i)

        with pytest.raises(IllegalCharacterError):
            cell.value = "A {0} B".format(chr(i))

    cell.value = chr(33)
    cell.value = chr(9)  # Tab
    cell.value = chr(10)  # Newline
    cell.value = chr(13)  # Carriage return
    cell.value = " Leading and trailing spaces are legal "
Exemple #34
0
                                corrected_acids.add(
                                    str(row[start_col_idx].value))
                        if type(value) in [int, float]:
                            value = value * PARAMETERS['Multiplier']
                        if data['Type'] == 'Urine' and value != 'n.a.' and row_idx > start_row_idx + 2:
                            try:
                                value = float(value) / float(
                                    data['Creatinine'])
                            except TypeError:
                                print(
                                    'ERROR: Creatinine value for ID %s is not number.'
                                    % file_id)
                        amounts[acid_name] = value
                        if acid_name in acid_norms:
                            new_cell = Cell(new_ws)
                            new_cell.value = value
                            total_cell = Cell(total_ws)
                            total_cell.value = value

                            lbound, rbound = acid_norms[acid_name]
                            if float(value) < float(lbound):
                                new_cell.fill = yellow_fill
                                total_cell.fill = yellow_fill
                            elif float(value) <= float(rbound):
                                new_cell.fill = green_fill
                                total_cell.fill = green_fill
                            else:
                                new_cell.fill = red_fill
                                total_cell.fill = red_fill

                            new_row.append(new_cell)
def test_data_type_check(value, datatype):
    ws = build_dummy_worksheet()
    ws.parent._guess_types = True
    cell = Cell(ws, 'A', 1)
    cell.value = value
    assert cell.data_type == datatype
Exemple #36
0
def set_and_fill_cell(cell: Cell, cell_value: str) -> None:
    wrapped_alignment = Alignment(vertical=constants.VERCTICAL_TOP.value,
                                  wrap_text=True)
    cell.alignment = wrapped_alignment
    cell.value = cell_value
    set_borders_between_columns(cell)
Exemple #37
0
def get_value_from_placement_dict(attrib, placement_dict, week):
    black_solid_fill = PatternFill("solid", fgColor="3b3b3b")
    dark_grid_fill = PatternFill("darkGrid", fgColor="3b3b3b")
    wb = Workbook()
    ws = wb.active
    return_cell = Cell(ws)
    return_cell.value == ''
    if attrib == 'fields':
        return_cell.value == ''
    if re.search('\d{1,2}', str(attrib)):
        plan_weeks = placement_dict.get('plan_weeks')
        fact_weeks = list()
        for value in placement_dict['postclick']:
            fact_weeks.append(int(value['weeknumber']))
        if attrib in plan_weeks:
            return_cell.fill = dark_grid_fill
        if attrib in fact_weeks:
            return_cell.fill = dark_grid_fill
        if attrib in plan_weeks and attrib in fact_weeks:
            return_cell.fill = black_solid_fill
    if attrib in ('platform_site', 'description', 'format', 'plan_impressions',
                  'plan_reach', 'plan_clicks', 'plan_views', 'plan_budget'):
        return_cell.value = placement_dict.get(attrib)
    if attrib in ('fact_impressions', 'fact_clicks', "fact_reach",
                  "fact_views", 'fact_budget'):
        for value in placement_dict['postclick']:
            if value['weeknumber'] == week:
                return_cell.value = value.get(attrib)
    if attrib == "plan_cpm":
        if placement_dict.get(
                "plan_budget") is not None and placement_dict.get(
                    "plan_impressions"):
            return_cell.value = placement_dict.get(
                "plan_budget") * 1000 / placement_dict.get("plan_impressions")
        else:
            return_cell.value = "N/A"
    if attrib == "plan_cpt":
        if placement_dict.get(
                "plan_budget") is not None and placement_dict.get(
                    "plan_reach") is not None:
            return_cell.value = placement_dict.get(
                "plan_budget") * 1000 / placement_dict.get("plan_reach")
        else:
            return_cell.value = "N/A"
    if attrib == "plan_ctr":
        if placement_dict.get(
                "plan_clicks") is not None and placement_dict.get(
                    "plan_impressions") is not None:
            return_cell.value = placement_dict.get(
                "plan_clicks") / placement_dict.get("plan_impressions")
        else:
            return_cell.value = "N/A"
    if attrib == "plan_cpc":
        if placement_dict.get(
                "plan_budget") is not None and placement_dict.get(
                    "plan_clicks") is not None:
            return_cell.value = placement_dict.get(
                "plan_budget") / placement_dict.get("plan_clicks")
        else:
            return_cell.value = "N/A"
    if attrib == "plan_vtr":
        if placement_dict.get("plan_views") != 'N/A' and placement_dict.get(
                "plan_impressions") is not None:
            return_cell.value = placement_dict.get(
                "plan_views") / placement_dict.get("plan_impressions")
        else:
            return_cell.value = "N/A"
    if attrib == "plan_cpv":
        if placement_dict.get(
                "plan_budget"
        ) is not None and placement_dict.get("plan_views") != 'N/A':
            return_cell.value = placement_dict.get(
                "plan_budget") / placement_dict.get("plan_views")
        else:
            return_cell.value = "N/A"
    if attrib == "fact_cpm":
        for value in placement_dict['postclick']:
            if value['weeknumber'] == week:
                if value.get("fact_budget") is not None and value.get(
                        "fact_impressions") is not None:
                    return_cell.value = value.get(
                        "fact_budget") * 1000 / value.get("fact_impressions")
                else:
                    return_cell.value = "N/A"
    if attrib == "fact_cpt":
        for value in placement_dict['postclick']:
            if value['weeknumber'] == week:
                if value.get("fact_budget") is not None and value.get(
                        "fact_reach") is not None:
                    return_cell.value = value.get(
                        "fact_budget") * 1000 / value.get("fact_reach")
                else:
                    return_cell.value = "N/A"
    if attrib == "fact_ctr":
        for value in placement_dict['postclick']:
            if value['weeknumber'] == week:
                if value.get("fact_clicks") is not None and value.get(
                        "fact_impressions") is not None:
                    return_cell.value = value.get("fact_clicks") / value.get(
                        "fact_impressions")
                else:
                    return_cell.value = "N/A"
    if attrib == "fact_cpc":
        for value in placement_dict['postclick']:
            if value['weeknumber'] == week:
                if value.get("fact_budget") is not None and value.get(
                        "fact_clicks") is not None:
                    return_cell.value = value.get("fact_budget") / value.get(
                        "fact_clicks")
                else:
                    return_cell.value = "N/A"
    if attrib == 'fact_vtr':
        for value in placement_dict['postclick']:
            if value['weeknumber'] == week:
                if value.get("fact_views") is not None and value.get(
                        "fact_impressions") is not None:
                    return_cell.value = value.get("fact_views") / value.get(
                        "fact_impressions")
                else:
                    return_cell.value = "N/A"
    if attrib == "fact_cpv":
        for value in placement_dict['postclick']:
            if value['weeknumber'] == week:
                if value.get("fact_budget") is not None and value.get(
                        "fact_views") is not None:
                    return_cell.value = value.get("fact_budget") / value.get(
                        "fact_views")
                else:
                    return_cell.value = "N/A"
    if attrib == 'period':
        return_cell.value = str(len(
            placement_dict.get('plan_weeks'))) + " weeks"
    if attrib == 'fact_impressions_adriver':
        if placement_dict.get('adriver_id') is not None:
            return_cell.value = get_adriver_value(
                placement_dict.get('adriver_id'), week)
        else:
            return_cell.value = "N/A"
    return return_cell
def test_data_type_check(value, datatype):
    ws = build_dummy_worksheet()
    ws.parent._guess_types = True
    cell = Cell(ws, 'A', 1)
    cell.value = value
    assert cell.data_type == datatype
Exemple #39
0
    def parse_cell(self, element):
        value = element.find(self.VALUE_TAG)
        if value is not None:
            value = value.text
        formula = element.find(self.FORMULA_TAG)
        data_type = element.get('t', 'n')
        coordinate = element.get('r')
        self._col_count += 1
        style_id = element.get('s')

        # assign formula to cell value unless only the data is desired
        if formula is not None and not self.data_only:
            data_type = 'f'
            if formula.text:
                value = "=" + formula.text
            else:
                value = "="
            formula_type = formula.get('t')
            if formula_type:
                if formula_type != "shared":
                    self.ws.formula_attributes[coordinate] = dict(
                        formula.attrib)

                else:
                    si = formula.get(
                        'si')  # Shared group index for shared formulas

                    # The spec (18.3.1.40) defines shared formulae in
                    # terms of the following:
                    #
                    # `master`: "The first formula in a group of shared
                    #            formulas"
                    # `ref`: "Range of cells which the formula applies
                    #        to." It's a required attribute on the master
                    #        cell, forbidden otherwise.
                    # `shared cell`: "A cell is shared only when si is
                    #                 used and t is `shared`."
                    #
                    # Whether to use the cell's given formula or the
                    # master's depends on whether the cell is shared,
                    # whether it's in the ref, and whether it defines its
                    # own formula, as follows:
                    #
                    #  Shared?   Has formula? | In ref    Not in ref
                    # ========= ==============|======== ===============
                    #   Yes          Yes      | master   impl. defined
                    #    No          Yes      |  own         own
                    #   Yes           No      | master   impl. defined
                    #    No           No      |  ??          N/A
                    #
                    # The ?? is because the spec is silent on this issue,
                    # though my inference is that the cell does not
                    # receive a formula at all.
                    #
                    # For this implementation, we are using the master
                    # formula in the two "impl. defined" cases and no
                    # formula in the "??" case. This choice of
                    # implementation allows us to disregard the `ref`
                    # parameter altogether, and does not require
                    # computing expressions like `C5 in A1:D6`.
                    # Presumably, Excel does not generate spreadsheets
                    # with such contradictions.
                    if si in self.shared_formula_masters:
                        trans = self.shared_formula_masters[si]
                        value = trans.translate_formula(coordinate)
                    else:
                        self.shared_formula_masters[si] = Translator(
                            value, coordinate)

        style_array = None
        if style_id is not None:
            style_id = int(style_id)
            style_array = self.styles[style_id]

        if coordinate:
            row, column = coordinate_to_tuple(coordinate)
        else:
            row, column = self._row_count, self._col_count

        cell = Cell(self.ws, row=row, col_idx=column, style_array=style_array)
        self.ws._cells[(row, column)] = cell

        if value is not None:
            if data_type == 'n':
                value = _cast_number(value)
                if is_date_format(cell.number_format):
                    data_type = 'd'
                    value = from_excel(value, self.epoch)

            elif data_type == 'b':
                value = bool(int(value))
            elif data_type == 's':
                value = self.shared_strings[int(value)]
            elif data_type == 'str':
                data_type = 's'
            elif data_type == 'd':
                value = from_ISO8601(value)

        else:
            if data_type == 'inlineStr':
                child = element.find(self.INLINE_STRING)
                if child is not None:
                    data_type = 's'
                    richtext = Text.from_tree(child)
                    value = richtext.content

        if self.guess_types or value is None:
            cell.value = value
        else:
            cell._value = value
            cell.data_type = data_type
Exemple #40
0
    def parse_cell(self, element):
        value = element.find(self.VALUE_TAG)
        if value is not None:
            value = value.text
        formula = element.find(self.FORMULA_TAG)
        data_type = element.get('t', 'n')
        coordinate = element.get('r')
        style_id = element.get('s')

        # assign formula to cell value unless only the data is desired
        if formula is not None and not self.data_only:
            data_type = 'f'
            if formula.text:
                value = "=" + formula.text
            else:
                value = "="
            formula_type = formula.get('t')
            if formula_type:
                self.ws.formula_attributes[coordinate] = {'t': formula_type}
                si = formula.get('si')  # Shared group index for shared formulas
                if si:
                    self.ws.formula_attributes[coordinate]['si'] = si
                    if formula_type == "shared":
                        # The spec (18.3.1.40) defines shared formulae in
                        # terms of the following:
                        #
                        # `master`: "The first formula in a group of shared
                        #            formulas"
                        # `ref`: "Range of cells which the formula applies
                        #        to." It's a required attribute on the master
                        #        cell, forbidden otherwise.
                        # `shared cell`: "A cell is shared only when si is
                        #                 used and t is `shared`."
                        #
                        # Whether to use the cell's given formula or the
                        # master's depends on whether the cell is shared,
                        # whether it's in the ref, and whether it defines its
                        # own formula, as follows:
                        #
                        #  Shared?   Has formula? | In ref    Not in ref
                        # ========= ==============|======== ===============
                        #   Yes          Yes      | master   impl. defined
                        #    No          Yes      |  own         own
                        #   Yes           No      | master   impl. defined
                        #    No           No      |  ??          N/A
                        #
                        # The ?? is because the spec is silent on this issue,
                        # though my inference is that the cell does not
                        # receive a formula at all.
                        #
                        # For this implementation, we are using the master
                        # formula in the two "impl. defined" cases and no
                        # formula in the "??" case. This choice of
                        # implementation allows us to disregard the `ref`
                        # parameter altogether, and does not require
                        # computing expressions like `C5 in A1:D6`.
                        # Presumably, Excel does not generate spreadsheets
                        # with such contradictions.
                        try:
                            trans = self.shared_formula_masters[si]
                        except KeyError:
                            # This cell must be master
                            self.shared_formula_masters[si] = Translator(
                                value, coordinate)
                        else:
                            value = trans.translate_formula(coordinate)
                ref = formula.get('ref')  # Range for shared formulas
                if ref:
                    self.ws.formula_attributes[coordinate]['ref'] = ref


        style = {}
        if style_id is not None:
            style_id = int(style_id)
            style = self.styles[style_id]

        row, column = coordinate_to_tuple(coordinate)
        cell = Cell(self.ws, row=row, col_idx=column, **style)
        self.ws._cells[(row, column)] = cell

        if value is not None:
            if data_type == 'n':
                value = _cast_number(value)
            elif data_type == 'b':
                value = bool(int(value))
            elif data_type == 's':
                value = self.shared_strings[int(value)]
            elif data_type == 'str':
                data_type = 's'

        else:
            if data_type == 'inlineStr':
                data_type = 's'
                child = element.find(self.INLINE_STRING)
                if child is None:
                    child = element.find(self.INLINE_RICHTEXT)
                if child is not None:
                    value = child.text

        if self.guess_types or value is None:
            cell.value = value
        else:
            cell._value=value
            cell.data_type=data_type