Пример #1
0
        def _read_style():
            wb = load_workbook(path)
            if isinstance(sheet_name, (str_type, unicode_type)):
                sheet = wb[sheet_name]
            elif isinstance(sheet_name, int):
                sheet = wb.worksheets[sheet_name]
            else:
                raise TypeError(
                    "'sheet_name' must be a string or int, got {} instead".
                    format(type(sheet_name)))
            theme_colors = _get_scheme_colors_from_excel(wb)
            for col_index, col_name in enumerate(sf.columns, start=1):
                column_cell = sheet.cell(row=1, column=col_index)
                if use_openpyxl_styles:
                    style_object = column_cell
                else:
                    style_object = Styler.from_openpyxl_style(
                        column_cell, theme_colors, read_comments
                        and column_cell.comment)
                sf.columns[col_index - 1].style = style_object
                for row_index, sf_index in enumerate(sf.index, start=2):
                    current_cell = sheet.cell(row=row_index, column=col_index)
                    if use_openpyxl_styles:
                        style_object = current_cell
                    else:
                        style_object = Styler.from_openpyxl_style(
                            current_cell, theme_colors, read_comments
                            and current_cell.comment)
                    sf.at[sf_index, col_name].style = style_object
                    sf._rows_height[row_index] = sheet.row_dimensions[
                        row_index].height

                sf._columns_width[col_name] = sheet.column_dimensions[
                    sf._get_column_as_letter(sheet, col_name)].width
Пример #2
0
    def apply_style_by_indexes(self, indexes_to_style, cols_to_style=None, styler_obj=None, bg_color=utils.colors.white,
                               bold=False, font='Arial', font_size=12, font_color=utils.colors.black, protection=False,
                               number_format=None, underline=None):
        """Applies a certain style to the provided indexes in the dataframe in the provided columns

        :param indexes_to_style: indexes to apply the style to
        :param cols_to_style: the columns to apply the style to, if not provided all the columns will be styled
        :param bg_color: the color to use.
        :param bold: bold or not
        :param font_size: the font size
        :param font_color: the font color
        :param protection: to protect the cell from changes or not
        :param number_format: modify the number format
        :param underline: the type of text underline
        :return: self
        :rtype: StyleFrame
        """

        if styler_obj:
            if not isinstance(styler_obj, Styler):
                raise TypeError(
                    'styler_obj must be {}, got {} instead.'.format(Styler.__name__, type(styler_obj).__name__))
            styler_obj = styler_obj.create_style()
        else:
            warnings.warn(DEPRECATION_MSG, DeprecationWarning)

        default_number_formats = {pd.tslib.Timestamp: 'DD/MM/YY HH:MM',
                                  dt.date: 'DD/MM/YY',
                                  dt.time: 'HH:MM'}

        indexes_number_format = number_format
        values_number_format = number_format

        if cols_to_style and not isinstance(cols_to_style, (list, tuple)):
            cols_to_style = [cols_to_style]
        elif not cols_to_style:
            cols_to_style = list(self.data_df.columns)
            for i in indexes_to_style:
                if not number_format:
                    indexes_number_format = default_number_formats.get(type(i.value), utils.number_formats.general)

                i.style = styler_obj or Styler(bg_color=bg_color, bold=bold, font=font, font_size=font_size,
                                               font_color=font_color, protection=protection,
                                               number_format=indexes_number_format, underline=underline).create_style()

        if not isinstance(indexes_to_style, (list, tuple, pd.Index)):
            indexes_to_style = [indexes_to_style]

        for index in indexes_to_style:
            for col in cols_to_style:
                if not number_format:
                    values_number_format = default_number_formats.get(type(self.ix[index.value, col].value), utils.number_formats.general)

                self.ix[index.value, col].style = styler_obj or Styler(bg_color=bg_color, bold=bold, font=font,
                                                                       font_size=font_size, font_color=font_color,
                                                                       protection=protection,
                                                                       number_format=values_number_format,
                                                                       underline=underline).create_style()
        return self
Пример #3
0
 def __init__(self, value, styler=None):
     self.value = value
     if styler is None:
         if isinstance(self.value, pd_timestamp):
             self.style = Styler(number_format=utils.number_formats.default_date_time_format)
         elif isinstance(self.value, dt.date):
             self.style = Styler(number_format=utils.number_formats.default_date_format)
         elif isinstance(self.value, dt.time):
             self.style = Styler(number_format=utils.number_formats.default_time_format)
         else:
             self.style = Styler()
     else:
         self.style = styler
Пример #4
0
 def __init__(self, value, styler=None):
     self.value = value
     if styler is None:
         if isinstance(self.value, pd.tslib.Timestamp):
             self.style = Styler(number_format='DD/MM/YY HH:MM').create_style()
         elif isinstance(self.value, dt.date):
             self.style = Styler(number_format='DD/MM/YY').create_style()
         elif isinstance(self.value, dt.time):
             self.style = Styler(number_format='HH:MM').create_style()
         else:
             self.style = Styler().create_style()
     else:
         self.style = styler
Пример #5
0
    def apply_column_style(self, cols_to_style, styler_obj=None, bg_color=utils.colors.white, font="Arial", bold=False, font_size=12, protection=False,
                           font_color=utils.colors.black, style_header=False, number_format=utils.number_formats.general,
                           underline=None):
        """apply style to a whole column

        :param cols_to_style: the columns to apply the style to
        :param bg_color:the color to use
        :param bold: bold or not
        :param font_size: the font size
        :param font_color: the font color
        :param style_header: style the header or not
        :param number_format: style the number format
        :param protection: to protect the column from changes or not
        :param underline: the type of text underline
        :return: self
        :rtype: StyleFrame
        """

        if styler_obj:
            if not isinstance(styler_obj, Styler):
                raise TypeError(
                    'styler_obj must be {}, got {} instead.'.format(Styler.__name__, type(styler_obj).__name__))
            styler_obj = styler_obj.create_style()
        else:
            warnings.warn(DEPRECATION_MSG, DeprecationWarning)

        if not isinstance(cols_to_style, (list, tuple)):
            cols_to_style = [cols_to_style]
        if not all(col in self.columns for col in cols_to_style):
            raise KeyError("one of the columns in {} wasn't found".format(cols_to_style))
        for col_name in cols_to_style:
            if style_header:
                self.columns[self.columns.get_loc(col_name)].style = styler_obj or Styler(bg_color=bg_color, bold=bold,
                                                                                          font=font, font_size=font_size,
                                                                                          font_color=font_color,
                                                                                          protection=protection,
                                                                                          number_format=number_format,
                                                                                          underline=underline).create_style()
                self._custom_headers_style = True
            for index in self.index:
                if isinstance(self.ix[index, col_name].value, pd.tslib.Timestamp):
                    number_format = utils.number_formats.date_time
                elif isinstance(self.ix[index, col_name].value, dt.date):
                    number_format = utils.number_formats.date
                elif isinstance(self.ix[index, col_name].value, dt.time):
                    number_format = utils.number_formats.time_24_hours
                self.ix[index, col_name].style = styler_obj or Styler(bg_color=bg_color, bold=bold, font=font,
                                                                      font_size=font_size, protection=protection,
                                                                      font_color=font_color, number_format=number_format,
                                                                      underline=underline).create_style()
        return self
Пример #6
0
    def apply_headers_style(self, styler_obj=None, bg_color=utils.colors.white, bold=True, font="Arial", font_size=12,
                            font_color=utils.colors.black, protection=False, number_format=utils.number_formats.general,
                            underline=None):
        """Apply style to the headers only

        :param bg_color:the color to use
        :param bold: bold or not
        :param font_size: the font size
        :param font_color: the font color
        :param number_format: openpy_style_obj the number format
        :param protection: to protect the column from changes or not
        :param underline: the type of text underline
        :return: self
        :rtype: StyleFrame
        """

        if styler_obj:
            if not isinstance(styler_obj, Styler):
                raise TypeError(
                    'styler_obj must be {}, got {} instead.'.format(Styler.__name__, type(styler_obj).__name__))

            styler_obj = styler_obj.create_style()
        else:
            warnings.warn(DEPRECATION_MSG, DeprecationWarning)

        for column in self.data_df.columns:
            column.style = styler_obj or Styler(bg_color=bg_color, bold=bold, font=font, font_size=font_size,
                                                font_color=font_color, protection=protection, number_format=number_format,
                                                underline=underline).create_style()
        self._custom_headers_style = True
        return self
Пример #7
0
    def apply_column_style(self,
                           cols_to_style,
                           styler_obj,
                           style_header=False,
                           use_default_formats=True,
                           width=None,
                           overwrite_default_style=True):
        """apply style to a whole column

        :param str|list|tuple|set cols_to_style: the columns to apply the style to
        :param Styler styler_obj: the styler object that contains the style to be applied
        :param bool style_header: if True, style the headers as well
        :param bool use_default_formats: if True, use predefined styles for dates and times
        :param None|int|float width: non-default width for the given columns
        :param bool overwrite_default_style: If True, the default style (the style used when initializing StyleFrame)
            will be overwritten. If False then the default style and the provided style wil be combined using
            Styler.combine method.
        :return: self
        :rtype: StyleFrame
        """

        if not isinstance(styler_obj, Styler):
            raise TypeError('styler_obj must be {}, got {} instead.'.format(
                Styler.__name__,
                type(styler_obj).__name__))

        if not isinstance(cols_to_style, (list, tuple, set, pd.Index)):
            cols_to_style = [cols_to_style]
        if not all(col in self.columns for col in cols_to_style):
            raise KeyError(
                "one of the columns in {} wasn't found".format(cols_to_style))

        if overwrite_default_style:
            style_to_apply = styler_obj
        else:
            style_to_apply = Styler.combine(self._default_style, styler_obj)

        for col_name in cols_to_style:
            if style_header:
                self.columns[self.columns.get_loc(
                    col_name)].style = style_to_apply
                self._has_custom_headers_style = True
            for index in self.index:
                if use_default_formats:
                    if isinstance(self.at[index, col_name].value,
                                  pd_timestamp):
                        style_to_apply.number_format = utils.number_formats.date_time
                    elif isinstance(self.at[index, col_name].value, dt.date):
                        style_to_apply.number_format = utils.number_formats.date
                    elif isinstance(self.at[index, col_name].value, dt.time):
                        style_to_apply.number_format = utils.number_formats.time_24_hours

                self.at[index, col_name].style = style_to_apply

        if width:
            self.set_column_width(columns=cols_to_style, width=width)

        return self
Пример #8
0
   def __init__(self):
       """Initialise the class by creating an instance of each object."""
       self._ratio_index = (0.05, 0.1, 0.2, 0.5, 1, 2, 4, 8, 16, 32, 64) # pagal sita dydi turi kisti tasko atstumas nuo zoominimo centro
       self._zoom_level = self._ratio_index.index(4) # 0-dirbame su realiomis koordinatemis - kitur koordinates yra gaunamos atliekant dalyba... todel nera labai tikslios
       
       self._device_area = None # gtk.gdk.Rectangle()
       
       self._shapes = [] # shapes data
       self._index_rtree = Rtree() # shapes indexes in self._shapes
       
       self._offset = Point(0, 0) #- naudojamas ctx.translate() #device koordinates
 
       self._prj = GisProjection()
       self._styler = Styler(self)
       self._painter = Painter(self._styler)
       
       self._drag_to_center = True # jeigu norime kad resize metu (bus iskviestas set_device_area) butu iskvietsas center()
Пример #9
0
    def apply_style_by_indexes(self,
                               indexes_to_style,
                               styler_obj,
                               cols_to_style=None,
                               height=None,
                               complement_style=None,
                               complement_height=None,
                               overwrite_default_style=True):
        """Applies a certain style to the provided indexes in the dataframe in the provided columns

        :param list|tuple|int|Container indexes_to_style: indexes to which the provided style will be applied
        :param Styler styler_obj: the styler object that contains the style which will be applied to indexes in indexes_to_style
        :param None|str|list|tuple|set cols_to_style: the columns to apply the style to, if not provided all the columns will be styled
        :param None|int|float height: height for rows whose indexes are in indexes_to_style
        :param None|Styler complement_style: the styler object that contains the style which will be applied to indexes not in indexes_to_style
        :param None|int|float complement_height: height for rows whose indexes are not in indexes_to_style. If not provided then
            height will be used (if provided).
        :param bool overwrite_default_style: If True, the default style (the style used when initializing StyleFrame)
            will be overwritten. If False then the default style and the provided style wil be combined using
            Styler.combine method.
        :return: self
        :rtype: StyleFrame
        """

        if not isinstance(styler_obj, Styler):
            raise TypeError('styler_obj must be {}, got {} instead.'.format(
                Styler.__name__,
                type(styler_obj).__name__))

        if isinstance(indexes_to_style, (list, tuple, int)):
            indexes_to_style = self.index[indexes_to_style]

        elif isinstance(indexes_to_style, Container):
            indexes_to_style = pd.Index([indexes_to_style])

        default_number_formats = {
            pd_timestamp: utils.number_formats.default_date_time_format,
            dt.date: utils.number_formats.default_date_format,
            dt.time: utils.number_formats.default_time_format
        }

        orig_number_format = styler_obj.number_format

        if cols_to_style is not None and not isinstance(
                cols_to_style, (list, tuple, set)):
            cols_to_style = [cols_to_style]
        elif cols_to_style is None:
            cols_to_style = list(self.data_df.columns)

        if overwrite_default_style:
            style_to_apply = deepcopy(styler_obj)
        else:
            style_to_apply = Styler.combine(self._default_style, styler_obj)

        for index in indexes_to_style:
            if orig_number_format == utils.number_formats.general:
                style_to_apply.number_format = default_number_formats.get(
                    type(index.value), utils.number_formats.general)
            index.style = style_to_apply

            for col in cols_to_style:
                cell = self.iloc[self.index.get_loc(index),
                                 self.columns.get_loc(col)]
                if orig_number_format == utils.number_formats.general:
                    style_to_apply.number_format = default_number_formats.get(
                        type(cell.value), utils.number_formats.general)

                cell.style = style_to_apply

        if height:
            # Add offset 2 since rows do not include the headers and they starts from 1 (not 0).
            rows_indexes_for_height_change = [
                self.index.get_loc(idx) + 2 for idx in indexes_to_style
            ]
            self.set_row_height(rows=rows_indexes_for_height_change,
                                height=height)

        if complement_style:
            self.apply_style_by_indexes(
                self.index.difference(indexes_to_style), complement_style,
                cols_to_style,
                complement_height if complement_height else height)

        return self
Пример #10
0
    def __init__(self, obj, styler_obj=None):
        from_another_styleframe = False
        from_pandas_dataframe = False
        if styler_obj and not isinstance(styler_obj, Styler):
            raise TypeError('styler_obj must be {}, got {} instead.'.format(
                Styler.__name__,
                type(styler_obj).__name__))
        if isinstance(obj, pd.DataFrame):
            from_pandas_dataframe = True
            if obj.empty:
                self.data_df = deepcopy(obj)
            else:
                self.data_df = obj.applymap(
                    lambda x: Container(x, deepcopy(styler_obj))
                    if not isinstance(x, Container) else x)
        elif isinstance(obj, pd.Series):
            self.data_df = obj.apply(
                lambda x: Container(x, deepcopy(styler_obj))
                if not isinstance(x, Container) else x)
        elif isinstance(obj, (dict, list)):
            self.data_df = pd.DataFrame(obj).applymap(
                lambda x: Container(x, deepcopy(styler_obj))
                if not isinstance(x, Container) else x)
        elif isinstance(obj, StyleFrame):
            self.data_df = deepcopy(obj.data_df)
            from_another_styleframe = True
        else:
            raise TypeError("{} __init__ doesn't support {}".format(
                type(self).__name__,
                type(obj).__name__))
        self.data_df.columns = [
            Container(col, deepcopy(styler_obj))
            if not isinstance(col, Container) else deepcopy(col)
            for col in self.data_df.columns
        ]
        self.data_df.index = [
            Container(index, deepcopy(styler_obj))
            if not isinstance(index, Container) else deepcopy(index)
            for index in self.data_df.index
        ]

        if from_pandas_dataframe:
            self.data_df.index.name = obj.index.name

        self._columns_width = obj._columns_width if from_another_styleframe else {}
        self._rows_height = obj._rows_height if from_another_styleframe else {}
        self._has_custom_headers_style = obj._has_custom_headers_style if from_another_styleframe else False
        self._cond_formatting = []
        self._default_style = styler_obj or Styler()
        self._index_header_style = obj._index_header_style if from_another_styleframe else self._default_style

        self._known_attrs = {
            'at': self.data_df.at,
            'loc': self.data_df.loc,
            'iloc': self.data_df.iloc,
            'applymap': self.data_df.applymap,
            'groupby': self.data_df.groupby,
            'index': self.data_df.index,
            'columns': self.data_df.columns,
            'fillna': self.data_df.fillna
        }
Пример #11
0
    def to_excel(self,
                 excel_writer='output.xlsx',
                 sheet_name='Sheet1',
                 allow_protection=False,
                 right_to_left=False,
                 columns_to_hide=None,
                 row_to_add_filters=None,
                 columns_and_rows_to_freeze=None,
                 best_fit=None,
                 **kwargs):
        """Saves the dataframe to excel and applies the styles.

        :param str|pandas.ExcelWriter excel_writer: File path or existing ExcelWriter
        :param str sheet_name: Name of sheet the StyleFrame will be exported to
        :param bool right_to_left: sets the sheet to be right to left.
        :param None|str|list|tuple|set columns_to_hide: single column, list, set or tuple of columns to hide, may be column index (starts from 1)
                                column name or column letter.
        :param bool allow_protection: allow to protect the sheet and the cells that specified as protected.
        :param None|int row_to_add_filters: add filters to the given row, starts from zero (zero is to add filters to columns).
        :param None|str columns_and_rows_to_freeze: column and row string to freeze for example: C3 will freeze columns: A,B and rows: 1,2.
        :param None|str|list|tuple|set best_fit: single column, list, set or tuple of columns names to attempt to best fit the width
                                for.

        See Pandas.DataFrame.to_excel documentation about other arguments
        """

        # dealing with needed pandas.to_excel defaults
        header = kwargs.pop('header', True)
        index = kwargs.pop('index', False)
        startcol = kwargs.pop('startcol', 0)
        startrow = kwargs.pop('startrow', 0)
        na_rep = kwargs.pop('na_rep', '')

        def get_values(x):
            if isinstance(x, Container):
                return x.value
            else:
                try:
                    if np.isnan(x):
                        return na_rep
                    else:
                        return x
                except TypeError:
                    return x

        def within_sheet_boundaries(row=1, column='A'):
            return (1 <= int(row) <= sheet.max_row and 1 <=
                    cell.column_index_from_string(column) <= sheet.max_column)

        def get_range_of_cells(row_index=None, columns=None):
            if columns is None:
                start_letter = self._get_column_as_letter(
                    sheet, self.data_df.columns[0], startcol)
                end_letter = self._get_column_as_letter(
                    sheet, self.data_df.columns[-1], startcol)
            else:
                start_letter = self._get_column_as_letter(
                    sheet, columns[0], startcol)
                end_letter = self._get_column_as_letter(
                    sheet, columns[-1], startcol)
            if row_index is None:  # returns cells range for the entire dataframe
                start_index = startrow + 1
                end_index = start_index + len(self)
            else:
                start_index = startrow + row_index + 1
                end_index = start_index
            return '{start_letter}{start_index}:{end_letter}{end_index}'.format(
                start_letter=start_letter,
                start_index=start_index,
                end_letter=end_letter,
                end_index=end_index)

        if len(self.data_df) > 0:
            export_df = self.data_df.applymap(get_values)

        else:
            export_df = deepcopy(self.data_df)

        export_df.columns = [col.value for col in export_df.columns]
        # noinspection PyTypeChecker
        export_df.index = [row_index.value for row_index in export_df.index]
        export_df.index.name = self.data_df.index.name

        if isinstance(excel_writer, (str_type, unicode_type)):
            excel_writer = self.ExcelWriter(excel_writer)

        export_df.to_excel(excel_writer,
                           sheet_name=sheet_name,
                           engine='openpyxl',
                           header=header,
                           index=index,
                           startcol=startcol,
                           startrow=startrow,
                           na_rep=na_rep,
                           **kwargs)

        sheet = excel_writer.sheets[sheet_name]

        sheet.sheet_view.rightToLeft = right_to_left

        self.data_df.fillna(Container('NaN'), inplace=True)

        if index:
            if self.data_df.index.name:
                index_name_cell = sheet.cell(row=startrow + 1,
                                             column=startcol + 1)
                index_name_cell.style = self._index_header_style.to_openpyxl_style(
                )
            for row_index, index in enumerate(self.data_df.index):
                try:
                    style_to_apply = index.style.to_openpyxl_style()
                except AttributeError:
                    style_to_apply = index.style
                current_cell = sheet.cell(row=startrow + row_index + 2,
                                          column=startcol + 1)
                current_cell.style = style_to_apply
                if isinstance(index.style, Styler):
                    current_cell.comment = index.style.generate_comment()
                else:
                    if hasattr(index.style, 'comment'):
                        index.style.comment.parent = None
                        current_cell.comment = index.style.comment

            startcol += 1

        if header and not self._has_custom_headers_style:
            self.apply_headers_style(Styler.default_header_style())

        # Iterating over the dataframe's elements and applying their styles
        # openpyxl's rows and cols start from 1,1 while the dataframe is 0,0
        for col_index, column in enumerate(self.data_df.columns):
            try:
                style_to_apply = column.style.to_openpyxl_style()
            except AttributeError:
                style_to_apply = column.style
            column_header_cell = sheet.cell(row=startrow + 1,
                                            column=col_index + startcol + 1)
            column_header_cell.style = style_to_apply
            if isinstance(column.style, Styler):
                column_header_cell.comment = column.style.generate_comment()
            else:
                if hasattr(column.style, 'comment'):
                    column.style.comment.parent = None
                    column_header_cell.comment = column.style.comment
            for row_index, index in enumerate(self.data_df.index):
                current_cell = sheet.cell(row=row_index + startrow + 2,
                                          column=col_index + startcol + 1)
                data_df_style = self.data_df.at[index, column].style
                try:
                    if '=HYPERLINK' in unicode_type(current_cell.value):
                        data_df_style.font_color = utils.colors.blue
                        data_df_style.underline = utils.underline.single
                    else:
                        if best_fit and column.value in best_fit:
                            data_df_style.wrap_text = False
                            data_df_style.shrink_to_fit = False
                    try:
                        style_to_apply = data_df_style.to_openpyxl_style()
                    except AttributeError:
                        style_to_apply = data_df_style
                    current_cell.style = style_to_apply
                    if isinstance(data_df_style, Styler):
                        current_cell.comment = data_df_style.generate_comment()
                    else:
                        if hasattr(data_df_style, 'comment'):
                            data_df_style.comment.parent = None
                            current_cell.comment = data_df_style.comment
                except AttributeError:  # if the element in the dataframe is not Container creating a default style
                    current_cell.style = Styler().to_openpyxl_style()

        if best_fit:
            if not isinstance(best_fit, (list, set, tuple)):
                best_fit = [best_fit]
            self.set_column_width_dict({
                column: (max(self.data_df[column].astype(str).str.len()) +
                         self.A_FACTOR) * self.P_FACTOR
                for column in best_fit
            })

        for column in self._columns_width:
            column_letter = self._get_column_as_letter(sheet, column, startcol)
            sheet.column_dimensions[column_letter].width = self._columns_width[
                column]

        for row in self._rows_height:
            if within_sheet_boundaries(row=(row + startrow)):
                sheet.row_dimensions[startrow +
                                     row].height = self._rows_height[row]
            else:
                raise IndexError('row: {} is out of range'.format(row))

        if row_to_add_filters is not None:
            try:
                row_to_add_filters = int(row_to_add_filters)
                if not within_sheet_boundaries(row=(row_to_add_filters +
                                                    startrow + 1)):
                    raise IndexError('row: {} is out of rows range'.format(
                        row_to_add_filters))
                sheet.auto_filter.ref = get_range_of_cells(
                    row_index=row_to_add_filters)
            except (TypeError, ValueError):
                raise TypeError("row must be an index and not {}".format(
                    type(row_to_add_filters)))

        if columns_and_rows_to_freeze is not None:
            if not isinstance(columns_and_rows_to_freeze,
                              (str_type, unicode_type
                               )) or len(columns_and_rows_to_freeze) < 2:
                raise TypeError(
                    "columns_and_rows_to_freeze must be a str for example: 'C3'"
                )
            if not within_sheet_boundaries(
                    column=columns_and_rows_to_freeze[0]):
                raise IndexError("column: %s is out of columns range." %
                                 columns_and_rows_to_freeze[0])
            if not within_sheet_boundaries(row=columns_and_rows_to_freeze[1]):
                raise IndexError("row: %s is out of rows range." %
                                 columns_and_rows_to_freeze[1])
            sheet.freeze_panes = sheet[columns_and_rows_to_freeze]

        if allow_protection:
            sheet.protection.autoFilter = False
            sheet.protection.enable()

        # Iterating over the columns_to_hide and check if the format is columns name, column index as number or letter
        if columns_to_hide:
            if not isinstance(columns_to_hide, (list, set, tuple)):
                columns_to_hide = [columns_to_hide]

            for column in columns_to_hide:
                column_letter = self._get_column_as_letter(
                    sheet, column, startcol)
                sheet.column_dimensions[column_letter].hidden = True

        for cond_formatting in self._cond_formatting:
            sheet.conditional_formatting.add(
                get_range_of_cells(columns=cond_formatting.columns),
                cond_formatting.rule)

        return excel_writer
Пример #12
0
CONTENT_IMG_NAME = "lion.jpg"
STYLE_IMG_NAME = "starry-night.jpg"
OUTPUT_NAME = "test"
NUM_FRAMES = 24 * 12

custom_params = dict(
    max_dimsize=512,
    num_iters=100,
    content_weight=0.0,
    init_img_type='custom',
)

default_config = StyleConfig()
default_config.update(**custom_params)
styler = Styler(default_config, device)


def zoom(image, zoom_pixels):
    # PIL image -> remove borders -> resize -> PIL Image
    width, height = image.size
    left, right = zoom_pixels, width - zoom_pixels
    top, bottom = zoom_pixels, height - zoom_pixels
    return image.crop((left, top, right, bottom)).resize((width, height))


content_image = Image.open(util.content_img_path(CONTENT_IMG_NAME))
style_image = Image.open(util.style_img_path(STYLE_IMG_NAME))

last_frame_result = content_image
for frame in range(NUM_FRAMES):
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)

from styler import StyleConfig, Styler
import util

import torch
from PIL import Image

# set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

CONTENT_IMG_NAME = "lion.jpg"
STYLE_IMG_NAME = "starry-night.jpg"
OUTPUT_NAME = "test"

default_config = StyleConfig()
styler = Styler(default_config, device)

content_image = Image.open(util.content_img_path(CONTENT_IMG_NAME))
style_image = Image.open(util.style_img_path(STYLE_IMG_NAME))

output = styler.style(
    content_image,
    style_image,
)

util.imsave(output, name=OUTPUT_NAME)
Пример #14
0
import util

import torch
from PIL import Image

# set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

CONTENT_IMG_NAME = "lion.jpg"
STYLE_IMG_NAME = "starry-night.jpg"
OUTPUT_NAME = "test"
NUM_OCTAVES = 3

params = {
    "max_dimsize": 512,
}

default_config = StyleConfig()
default_config.update(**params)
styler = Styler(default_config, device)

content_image = Image.open(util.content_img_path(CONTENT_IMG_NAME))
style_image = Image.open(util.style_img_path(STYLE_IMG_NAME))

output = styler.style_multiscale(content_image,
                                 style_image,
                                 octaves=NUM_OCTAVES,
                                 save_intermediate=True)

util.imsave(output, name=OUTPUT_NAME)
Пример #15
0
from interactions import *
from information import *
from styler import Styler

import time

s = Styler()

Header("CLImate Demo").display()
time.sleep(0.5)
Message(Message.tags.info, "Welcome to the CLImate component demo").display()
print()
time.sleep(2)

Header("Message Demo", align="left", pattern_color=s.colors.purple).display()
time.sleep(0.5)
Message(
    Message.tags.info,
    "{} messages are all tagged to help organize output".format(
        s.apply("CLImate", s.mods.bold, s.colors.pink)),
).display()
time.sleep(0.5)
Message(Message.tags.info, "Let's take a look at them").display()
time.sleep(4.5)
print()

Message(Message.tags.start, "Some process").display()
time.sleep(1)
Message(Message.tags.info,
        "Here, let's look at how far along we are").display()
time.sleep(0.5)
Пример #16
0
class GisCanvas:
    """
    Top-level drawing class that contains a list of all the objects to draw.
    """
    def __init__(self):
        """Initialise the class by creating an instance of each object."""
        self._ratio_index = (0.05, 0.1, 0.2, 0.5, 1, 2, 4, 8, 16, 32, 64) # pagal sita dydi turi kisti tasko atstumas nuo zoominimo centro
        self._zoom_level = self._ratio_index.index(4) # 0-dirbame su realiomis koordinatemis - kitur koordinates yra gaunamos atliekant dalyba... todel nera labai tikslios
        
        self._device_area = None # gtk.gdk.Rectangle()
        
        self._shapes = [] # shapes data
        self._index_rtree = Rtree() # shapes indexes in self._shapes
        
        self._offset = Point(0, 0) #- naudojamas ctx.translate() #device koordinates
  
        self._prj = GisProjection()
        self._styler = Styler(self)
        self._painter = Painter(self._styler)
        
        self._drag_to_center = True # jeigu norime kad resize metu (bus iskviestas set_device_area) butu iskvietsas center()

        
    def load(self, name):
        self._styler.load_css_file("%s.css" % name)
        self.load_fcad_file("%s.fcad" % name)

        
    def save(self, file_name):
        #self.create_fcad_file("%s.fcad" % file_name)
        ShapeFile.create_fcad_file("%s.fcad" % file_name, self._shapes)
        StyleFile.create_css_file("%s.css" % file_name, self._styler.get_shapes_style(), self._styler.get_symbols_style(), prettyprint=True)
        
        #self._styler.create_css_file("%s.css" % file_name, prettyprint=True)
        
        
        
    def clear(self):
        print "clear canvas!"
        self._zoom_level = self._ratio_index.index(1)
        self._offset = Point(0, 0)
       
        self._shapes = []
        #self._cairo_paths = {}
        self._index_rtree = Rtree()
        self._styler.load_default_style()

       
    def load_pickle(self, file_path):
        timer.start("loading shapes.p")
        if os.path.exists(file_path):
            self._shapes = pickle.load(open(file_path, "rb"))
            
            if len(self._shapes):
                def generator_function(points):
                    for i, obj in enumerate(points):
                        if obj == None: continue
                        yield (i, self._styler.get_bbox(fshape.Shape.decompress(obj)), obj)
                self._index_rtree = Rtree(generator_function(self._shapes))
        timer.end("loading shapes.p")

        
    def save_pickle(self, file_path):
        pickle.dump(self._shapes, open(file_path, "wb"))

        
    def load_fcad_file(self, file_path):
        timer.start("loading shapes.fcad")
        self._shapes = ShapeFile.read_fcad_file(file_path)
    
        if len(self._shapes):
            def generator_function(points):
                for i, obj in enumerate(points):
                    if obj == None: continue
                    yield (i, self._styler.get_bbox(fshape.Shape.decompress(obj)), obj)
            self._index_rtree = Rtree(generator_function(self._shapes))
        timer.end("loading shapes.fcad")
     
     
    def set_device_area(self, area): # atnaujina screen.resize()
        self._device_area = area
        
        if self._drag_to_center:
            self.center()
            self._drag_to_center = False


    def get_shape_by_id(self, id):
        compressed_shape = self._shapes[id]
        if compressed_shape == None: return None
        return fshape.Shape.decompress(compressed_shape)

        
    def get_object_by_id(self, id):
        return self._shapes[id]

        
    def draw_100(self, ctx, area):
        """100% draw for printing, no scale, area in user coordinates"""
        page_area = Area(0, 0, area.width, area.height)
        #ctx.rectangle(0, 0, area.width, area.height) 
        #ctx.clip() # tam kad nepaisytu uzh sito staciakampio ribu (tada gaunasi dubliuotos linijos)
        #self.background(ctx, page_area) # paint white background
        
        self._painter.background(ctx, page_area, color=(1,1,1), clip=True) # paint white background
        self._painter.setup(ctx, transform={"translate":(-area.x, -area.y)})

        radius = 0 #self.pixel_radius + self.line_width # ne cia reikia prideti radiusa, o ten kur dedame i cavas'a shape'us
        
        elements = self._index_rtree.intersection((area.x-radius, area.y-radius, area.x+area.width+radius, area.y+area.height+radius))
        elements_zindex = self._styler.create_zindex(elements) # jis yra pilnas visu galimu zindex'u sarasas - pradzioje dalis ju gali buti ir tusti []
        
        timer.start("draw100")
        for zindex in sorted(elements_zindex.keys()):
            for element in elements_zindex[zindex]:
                self._painter.draw(element, update=elements_zindex) # kazka visada nupaiso - bet dar papildomai gali iterpti elementu su didesniu zindex'u
                # tie elementai bus nupaisomi veliau.
            
        timer.end("draw100")
            
            
    
    
    def draw_object(self, ctx, id, fill_or_stroke=True):
        #self.apply_transforms(ctx) # drag and scale
        self._painter.setup(ctx, transform={"translate":self.get_offset(), "scale": self.get_ratio()})
        
        elements_zindex = self._styler.create_zindex([id])
        
        timer.start("draw single object")
        for zindex in sorted(elements_zindex.keys()):
            for element in elements_zindex[zindex]:
                self._painter.draw(element, update=elements_zindex, fill_or_stroke=fill_or_stroke) # kazka visada nupaiso - bet dar papildomai gali iterpti elementu su didesniu zindex'u
            
        timer.end("draw single object")
    

    def draw(self, ctx, area, fill_or_stroke=True):
        """Draw the complete drawing by drawing each object in turn."""
        
        self._painter.background(ctx, area, color=(1,1,1), clip=True) # paint white background
        self._painter.setup(ctx, transform={"translate":self.get_offset(), "scale": self.get_ratio()})
        
        # paishysime tik tuos tashkus kurie pakliuna i vartotojo langa
        # reikia device_area konvertuoti i user koordinates
        x, y = self.device_to_user(Point(area.x, area.y))
        x2, y2 = self.device_to_user(Point(area.x + area.width, area.y + area.height))
        
        radius = 0 #self.pixel_radius + self.line_width # ne cia reikia prideti radiusa, o ten kur dedame i cavas'a shape'us
        # geriau cia, nes paprasciau yra iskviesti nupaisyti didesni gabala nei paskaiciuoti tikslu pvz linijo simboliu dydi...
        
        elements = self._index_rtree.intersection((x-radius, y-radius, x2+radius, y2+radius))
        elements_zindex = self._styler.create_zindex(elements) # jis yra pilnas visu galimu zindex'u sarasas - pradzioje dalis ju gali buti ir tusti []
        
        timer.start("draw")
        for zindex in sorted(elements_zindex.keys()):
            for element in elements_zindex[zindex]:
                #print "element: ", element[0][0]
                self._painter.draw(element, update=elements_zindex, fill_or_stroke=fill_or_stroke) # kazka visada nupaiso - bet dar papildomai gali iterpti elementu su didesniu zindex'u
                # tie elementai bus nupaisomi veliau.
            
        timer.end("draw")
        
        
        
    def get_ratio(self, level=None):
        if level == None: level = self._zoom_level 
        return self._ratio_index[level]

    
    def drag2(self, drag_offset):
        self._offset = Point(self._offset.x + drag_offset.x, self._offset.y + drag_offset.y)
    
        
    def get_offset(self):
        return self._offset


    def find_objects_at_position(self, point):
        #ctx = self.get_context(transform=False) # naujas kontekstas kur paisysime, transformuoti nereikia - nes tai padarys .draw()
        ctx = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 0,  0)) # naujas kontekstas kur paisysime, transformuoti nereikia - nes tai padarys .draw()
      
        area = Area(point.x, point.y, 1, 1)

        listener = ContextObjectsListener(point)
        listener_id = self._painter.addContextListener(listener)

        try:
            self.draw(ctx, area, fill_or_stroke=False) # nepaisysime tik sukursime path'us context'e ir su jais kazka atliks ContextListeneris
        finally:
            self._painter.removeContextListener(listener_id)
        
        return listener.get_objects() # rastu elementu indeksai

        
    def get_shape_redraw_area(self, id):
        #ctx = self.get_context(transform=False)
        ctx = cairo.Context(cairo.ImageSurface(cairo.FORMAT_ARGB32, 0,  0))
        
        shape = self.get_object_by_id(id)
        if shape == None: return None
        
        listener = ContextBoundsListener()
        listener_id = self._painter.addContextListener(listener)
        
        try:
            self.draw_object(ctx, id, fill_or_stroke=False)
        finally:
            self._painter.removeContextListener(listener_id)
            
        area = listener.get_area()
        #print "Area: ", area
        return area
        
        
    def device_to_user(self, point):
        #x, y = self.ctx.device_to_user(point.x, point.y)
        #x, y = self.get_context().device_to_user(point.x, point.y)
        
        ratio = self.get_ratio()
        offset = self.get_offset()
        x, y = (point.x - offset.x)/ratio, (point.y - offset.y)/ratio
        
        return Point(x, y)

        
    def user_to_device(self, point, offset=(0, 0)):
        #x, y = self.ctx.user_to_device(point.x, point.y)
        #x, y = self.get_context().user_to_device(point.x, point.y)
        
        ratio = self.get_ratio()
        drag_offset = self.get_offset()
        x, y = (point.x  * ratio) + drag_offset.x, (point.y  * ratio) + drag_offset.y
        
        return Point(x + offset[0], y + offset[1])

    
    def add(self, shape):
        id = len(self._shapes) # top element index
        self._shapes.append(shape.compress())
        self._index_rtree.add(id, self._styler.get_bbox(shape))
        return id

        
    def remove(self, id):
        shape = self.get_shape_by_id(id)
        self._index_rtree.delete(id, shape.bbox()) # po sito as jau niekada tokio id negausiu (nes viskas eina per rtree)
        self._shapes[id] = None

        
    def replace(self, id, shape):
        old = self.get_shape_by_id(id)
        #print "before :", list(self._index_rtree.intersection(old.bbox())) 
        if old != None:
            self._index_rtree.delete(id, old.bbox())
        #print "after :", list(self._index_rtree.intersection(old.bbox()))
        self._shapes[id] = shape.compress()
        self._index_rtree.add(id, self._styler.get_bbox(shape))
    
        
    def zoom(self, direction, center=None):
        """center cia yra device koordinatemis - jeigu butu paspausta su zoom irankiu peles pagalba"""
        new_zoom_level = self._zoom_level+direction
        if new_zoom_level in range(0, len(self._ratio_index)):
            #esamas centro taskas atlikus zooma turi islikti toje pacioje vietoje
            center = center or Point(self._device_area.width/2, self._device_area.height/2) # vartotojo parinktas tashkas arba tiesiog centras
            center_user = self.device_to_user(center)
            
            # gauname priesh tai buvusio centro koordinates naujame zoom lygyje
            new_ratio = self.get_ratio(new_zoom_level)
            new_center = Point(center_user.x * new_ratio, center_user.y * new_ratio)
                
            # gauname centro poslinki (per tiek reikia perstumti visa vaizdeli)
            self._offset = Point(center.x - new_center.x, center.y - new_center.y) # naujas poslinkis
            #print "zoom: ", self._offset
            self._zoom_level = new_zoom_level
            return True
        return False


    def center(self, point=None):
        """center to user point"""
        if not point:
            bounds = self._index_rtree.bounds
            point = Point((bounds[0]+bounds[2])/2.0, (bounds[1]+bounds[3])/2.0)
        
        hand = self.user_to_device(point)
        to = Point(self._device_area.width/2, self._device_area.height/2)
        self.drag2(Point(to.x-hand.x, to.y-hand.y))

        
    def get_projection(self):
        return self._prj
        
    def get_styler(self):
        return self._styler

        
    def load_ocad_file(self, file_path, generator=True):
        #import ocadfile
        #self.add(Shape(1, Point(0, 0), symbol="graphics")) # koordinaciu centras

        self._prj = GisProjection()
        self._zoom_level = self._ratio_index.index(4)
        
        of = OcadFile(file_path, self._prj)
        #self._styler.load_ocad_symbols(of, prj)

        timer.start("Adding ocad symbols")
        self._styler.set_symbols_style(of.get_symbols_style())
        timer.end("Adding ocad symbols")
        
        
        timer.start("Adding ocad elements")
        shapes = of.get_shapes()
        print "Shapes: ", len(shapes)
        for shape in shapes:
            self.add(shape)
        timer.end("Adding ocad elements")
        
        self.center()

        
    def load_shape_file(self, file_path, generator=True):
        import shapefile
        from random import randint

        sf = shapefile.Reader(file_path)
        print "Number of shapes: ", sf.numRecords
        
        self.add(fshape.Shape(1, Point(0, 0), style={"z-index":99})) # koordinaciu centras
        
        if self.prj.scale == 1: # pirmas kartas
            prj = GisProjection(self, sf.bbox)
            #po sito ciklo jau turesime zemelapio ribas
            center = prj.map_to_user(prj.get_center())
            self.center(center)
            self.prj = prj
                    
        timer.start("Adding shapes")
        symbol = sf.shapeName.split("/")[-1]
        self._styler.set_symbol_style(symbol, {"color": (randint(0,255),randint(0,255),randint(0,255))})
        
        for shape in sf.ogis_shapes(self.prj):
            self.add(fshape.Shape(shape.shapeType, shape.points, symbol=symbol))
        timer.end("Adding shapes")
                    
        

    def add_random_points(self, number, area, generator=True):
        """Kai generator=False - sunaudoja maziau atminties ikrovimo metu, bet trunka gerokai leciau
        """
        self._shapes = []
        timer.start("Adding random data")

        from random import randint
        for x in range(0, number):
            color = 65536 * randint(0,255) + 256 * randint(0,255) + randint(0,255) # RGBint
            x, y = randint(2, area.width), randint(2, area.height)

            if not generator: # darysime rtree.add kiekvienam taskui atskirai
                self.add(fshape.Shape(1, Point(x, y), color=color))
            else:
                self._shapes.append((1, color, x, y))
        
        if generator:
            def generator_function(points):
                for i, obj in enumerate(points):
                    yield (i, (obj[2], obj[3], obj[2], obj[3]), obj)
            self._index_rtree = Rtree(generator_function(self._shapes))
        
        timer.end("Adding random data")
Пример #17
0
from .message import Message
from styler import Styler

# In order to solve issue #2
s = Styler()


class LoadingSpinner(Message):
    """
    A loading spinner to add to message so that the user knows he has to wait.

    Parameters:
    -----------
    tag (tags): The tage of the message to use
    info (str): The info to print
    spinner (str): The type of spinner. Use one of ('bar', 'dot', 'equal')
    """
    def __init__(self, tag, info, spinner='bar'):
        self.text = info
        Message.__init__(self, tag, info, "\r")
        if spinner == 'bar':
            self.spinner = ['/', '-', '\\', '|']
        elif spinner == 'dot':
            self.spinner = ['   ', '.  ', '.. ', '...', ' ..', '  .']
        elif spinner == 'equal':
            self.spinner = [
                '[   ]', '[=  ]', '[== ]', '[===]', '[ ==]', '[  =]'
            ]
        else:
            raise ValueError("'spinner' can't be {}.".format(spinner))
        self.count = 0
Пример #18
0
    def to_excel(self,
                 excel_writer='output.xlsx',
                 sheet_name='Sheet1',
                 na_rep='',
                 float_format=None,
                 columns=None,
                 header=True,
                 index=False,
                 index_label=None,
                 startrow=0,
                 startcol=0,
                 merge_cells=True,
                 encoding=None,
                 inf_rep='inf',
                 allow_protection=False,
                 right_to_left=False,
                 columns_to_hide=None,
                 row_to_add_filters=None,
                 columns_and_rows_to_freeze=None):
        """Saves the dataframe to excel and applies the styles.

        :param right_to_left: sets the sheet to be right to left.
        :param columns_to_hide: single column, list or tuple of columns to hide, may be column index (starts from 1)
                                column name or column letter.
        :param allow_protection: allow to protect the sheet and the cells that specified as protected.
        :param row_to_add_filters: add filters to the given row, starts from zero (zero is to add filters to columns).
        :param columns_and_rows_to_freeze: column and row string to freeze for example: C3 will freeze columns: A,B and rows: 1,2.

        See Pandas' to_excel documentation about the other parameters
        """
        def get_values(x):
            if isinstance(x, Container):
                return x.value
            else:
                try:
                    if np.isnan(x):
                        return na_rep
                    else:
                        return x
                except TypeError:
                    return x

        def get_column_as_letter(column_to_convert):
            if not isinstance(column_to_convert,
                              (int, basestring if PY2 else str, Container)):
                raise TypeError(
                    "column must be an index, column letter or column name")
            column_as_letter = None
            if column_to_convert in self.data_df.columns:  # column name
                column_index = self.data_df.columns.get_loc(
                    column_to_convert
                ) + startcol + 1  # worksheet columns index start from 1
                column_as_letter = cell.get_column_letter(column_index)

            elif isinstance(column_to_convert,
                            int) and column_to_convert >= 1:  # column index
                column_as_letter = cell.get_column_letter(startcol +
                                                          column_to_convert)
            elif column_to_convert in sheet.column_dimensions:  # column letter
                column_as_letter = column_to_convert

            if column_as_letter is None or column_as_letter not in sheet.column_dimensions:
                raise IndexError("column: %s is out of columns range." %
                                 column_to_convert)

            return column_as_letter

        def get_range_of_cells_for_specific_row(row_index):
            start_letter = get_column_as_letter(
                column_to_convert=self.data_df.columns[0])
            end_letter = get_column_as_letter(
                column_to_convert=self.data_df.columns[-1])
            return '{start_letter}{start_index}:{end_letter}{end_index}'.format(
                start_letter=start_letter,
                start_index=startrow + row_index + 1,
                end_letter=end_letter,
                end_index=startrow + row_index + 1)

        if len(self.data_df) > 0:
            export_df = self.data_df.applymap(get_values)

        else:
            export_df = deepcopy(self.data_df)

        export_df.columns = [col.value for col in export_df.columns]
        # noinspection PyTypeChecker
        export_df.index = [row_index.value for row_index in export_df.index]

        if isinstance(excel_writer, basestring if PY2 else str):
            excel_writer = self.ExcelWriter(excel_writer)

        export_df.to_excel(excel_writer,
                           sheet_name=sheet_name,
                           na_rep=na_rep,
                           float_format=float_format,
                           index=index,
                           columns=columns,
                           header=header,
                           index_label=index_label,
                           startrow=startrow,
                           startcol=startcol,
                           engine='openpyxl',
                           merge_cells=merge_cells,
                           encoding=encoding,
                           inf_rep=inf_rep)

        sheet = excel_writer.book.get_sheet_by_name(sheet_name)

        sheet.sheet_view.rightToLeft = right_to_left

        self.data_df.fillna(Container('NaN'), inplace=True)

        if index:
            for row_index, index in enumerate(self.data_df.index):
                sheet.cell(row=startrow + row_index + 2,
                           column=startcol + 1).style = index.style
            startcol += 1

        if header and not self._custom_headers_style:
            self.apply_headers_style(Styler.default_header_style())

        # Iterating over the dataframe's elements and applying their styles
        # openpyxl's rows and cols start from 1,1 while the dataframe is 0,0
        for col_index, column in enumerate(self.data_df.columns):
            sheet.cell(row=startrow + 1,
                       column=col_index + startcol + 1).style = column.style

            for row_index, index in enumerate(self.data_df.index):
                current_cell = sheet.cell(row=row_index + startrow + 2,
                                          column=col_index + startcol + 1)
                try:
                    if PY2:
                        if '=HYPERLINK' in unicode(current_cell.value):
                            current_bg_color = current_cell.style.fill.fgColor.rgb
                            current_font_size = current_cell.style.font.size
                            current_cell.style = Styler(
                                bg_color=current_bg_color,
                                font_color=utils.colors.blue,
                                font_size=current_font_size,
                                number_format=utils.number_formats.general,
                                underline=utils.underline.single).create_style(
                                )
                        else:
                            current_cell.style = self.data_df.loc[index,
                                                                  column].style

                    else:
                        if '=HYPERLINK' in str(current_cell.value):
                            current_bg_color = current_cell.style.fill.fgColor.rgb
                            current_font_size = current_cell.style.font.size
                            current_cell.style = Styler(
                                bg_color=current_bg_color,
                                font_color=utils.colors.blue,
                                font_size=current_font_size,
                                number_format=utils.number_formats.general,
                                underline='single').create_style()
                        else:
                            current_cell.style = self.data_df.loc[index,
                                                                  column].style

                except AttributeError:  # if the element in the dataframe is not Container creating a default style
                    current_cell.style = Styler().create_style()

        for column in self._columns_width:
            column_letter = get_column_as_letter(column_to_convert=column)
            sheet.column_dimensions[column_letter].width = self._columns_width[
                column]

        for row in self._rows_height:
            if row + startrow in sheet.row_dimensions:
                sheet.row_dimensions[startrow +
                                     row].height = self._rows_height[row]
            else:
                raise IndexError('row: {} is out of range'.format(row))

        if row_to_add_filters is not None:
            try:
                row_to_add_filters = int(row_to_add_filters)
                if (row_to_add_filters + startrow +
                        1) not in sheet.row_dimensions:
                    raise IndexError('row: {} is out of rows range'.format(
                        row_to_add_filters))
                sheet.auto_filter.ref = get_range_of_cells_for_specific_row(
                    row_index=row_to_add_filters)
            except (TypeError, ValueError):
                raise TypeError("row must be an index and not {}".format(
                    type(row_to_add_filters)))

        if columns_and_rows_to_freeze is not None:
            if not isinstance(columns_and_rows_to_freeze, basestring if PY2
                              else str) or len(columns_and_rows_to_freeze) < 2:
                raise TypeError(
                    "columns_and_rows_to_freeze must be a str for example: 'C3'"
                )
            if columns_and_rows_to_freeze[0] not in sheet.column_dimensions:
                raise IndexError("column: %s is out of columns range." %
                                 columns_and_rows_to_freeze[0])
            if int(columns_and_rows_to_freeze[1]) not in sheet.row_dimensions:
                raise IndexError("row: %s is out of rows range." %
                                 columns_and_rows_to_freeze[1])
            sheet.freeze_panes = sheet[columns_and_rows_to_freeze]

        if allow_protection:
            sheet.protection.autoFilter = False
            sheet.protection.enable()

        # Iterating over the columns_to_hide and check if the format is columns name, column index as number or letter
        if columns_to_hide:
            if not isinstance(columns_to_hide, (list, tuple)):
                columns_to_hide = [columns_to_hide]

            for column in columns_to_hide:
                column_letter = get_column_as_letter(column_to_convert=column)
                sheet.column_dimensions[column_letter].hidden = True

        return excel_writer