How to use the openpyxl.styles.Alignment function in openpyxl

To help you get started, we’ve selected a few openpyxl examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wind39 / spartacus / tests / test_report_lowmem.py View on Github external
exit(0)

    v_workBook = openpyxl.Workbook()
    v_workBook.remove(v_workBook.active)

    v_workSheet = v_workBook.create_sheet(v_sheetName)
    v_workSheet.sheet_view.showGridLines = False

    # v_workSheet.add_image(
    #    openpyxl.drawing.image.Image('/path/to/image.png'),
    #    'A1'
    # )

    v_boldFont = openpyxl.styles.Font(bold=True)

    v_centerAlignment = openpyxl.styles.Alignment(
        horizontal="center", vertical="center", wrapText=True
    )

    v_workSheet.merge_cells("A2:F2")
    v_workSheet["A2"] = bs4.BeautifulSoup(v_reportName, "lxml").get_text()
    v_workSheet["A2"].font = v_boldFont
    v_workSheet["A2"].alignment = v_centerAlignment

    v_headerFont = openpyxl.styles.Font(bold=True)

    v_headerFill = openpyxl.styles.PatternFill("solid", fgColor="DBE5F1")

    v_headerAlignment = openpyxl.styles.Alignment(
        horizontal="center", vertical="center", wrapText=True
    )
github patarapolw / pyexcel-export / pyexcel_export / formatter.py View on Github external
wrap_text = True
                            else:
                                continue

                            if cell.value is not None:
                                mul = 0
                                for v in str(cell.value).split('\n'):
                                    mul += math.ceil(len(v) / col_width[j]) * cell.font.size

                                if mul > 0:
                                    multiples_of_font_size.append(mul)

                        if rules.get('align_top', DEFAULTS['align_top']):
                            vertical = "top"

                        cell.alignment = Alignment(wrap_text=wrap_text, vertical=vertical)

                    original_height = ws.row_dimensions[i+1].height
                    if original_height is None:
                        original_height = default_height

                    new_height = max(multiples_of_font_size)
                    max_height = rules.get('maximum_row_height', DEFAULTS['maximum_row_height'])
                    if original_height < new_height or rules.get('reset_height', False):
                        if new_height < max_height:
                            ws.row_dimensions[i + 1].height = new_height
                        else:
                            ws.row_dimensions[i + 1].height = max_height
github Metatab / metatab / metapack / package / excel.py View on Github external
meta_ws.column_dimensions['E'].width = 20

        self.sections.resources.sort_by_term()

        self.load_declares()

        self.doc.cleanse()

        self._load_resources()

        self._clean_doc()

        fill = PatternFill("solid", fgColor="acc0e0")  # PatternFill(patternType='gray125')
        table_fill = PatternFill("solid", fgColor="d9dce0")  # PatternFill(patternType='gray125')

        alignment = Alignment(wrap_text=False)
        for i, row in enumerate(self.doc.rows, 1):

            if row[0] == 'Section' or row[0] == 'Table':
                styled_row = []
                for c in row + [''] * 5:
                    cell = WriteOnlyCell(meta_ws, value=c)
                    cell.fill = fill if row[0] == 'Section' else table_fill
                    styled_row.append(cell)
                meta_ws.append(styled_row)


            else:
                meta_ws.append(row)


        self.wb.save(self.package_path.path)
github doorstop-dev / doorstop / doorstop / core / exporter.py View on Github external
"""
    col_widths = defaultdict(int)
    col = 'A'

    # Create a new workbook
    workbook = openpyxl.Workbook()
    worksheet = workbook.active

    # Populate cells
    for row, data in enumerate(_tabulate(obj, auto=auto), start=1):
        for col_idx, value in enumerate(data, start=1):
            cell = worksheet.cell(column=col_idx, row=row)

            # wrap text in every cell
            alignment = openpyxl.styles.Alignment(
                vertical='top', horizontal='left', wrap_text=True
            )
            cell.alignment = alignment
            # and bold header rows
            if row == 1:
                cell.font = openpyxl.styles.Font(bold=True)

            # convert incompatible Excel types:
            # http://pythonhosted.org/openpyxl/api.html#openpyxl.cell.Cell.value
            if isinstance(value, (int, float, datetime.datetime)):
                cell.value = value
            else:
                cell.value = str(value)

            # track cell width
            col_widths[col_idx] = max(col_widths[col_idx], _width(str(value)))
github censusreporter / census-api / census_extractomatic / exporters.py View on Github external
# get column headers
        for column_id, column_info in table['columns'].iteritems():
            column_name_utf8 = column_info['name'].encode('utf-8')
            indent = column_info['indent']

            header.append((column_name_utf8, indent))

            if indent > max_indent:
                max_indent = indent

        # Populate first column with headers
        for i, col_tuple in enumerate(header):
            current_row = i + 4 # 1-based index, account for geographic headers
            current_cell = sheet.cell(row=current_row, column=1)
            current_cell.value = col_tuple[0]
            current_cell.alignment = Alignment(indent=col_tuple[1], wrap_text=True)

        # Resize column width
        sheet.column_dimensions['A'].width = 50

        # this SQL echoed in OGR export but no geom so copying instead of factoring out
        # plus different binding when using SQLAlchemy
        result = session(sql_url).execute(
            """SELECT full_geoid,display_name
                     FROM tiger2014.census_name_lookup
                     WHERE full_geoid IN :geoids
                     ORDER BY full_geoid""",
            {'geoids': tuple(valid_geo_ids)}
        )

        geo_headers = []
        for i, (geoid, name) in enumerate(result):
github performancecopilot / pcp / src / pcp2xlsx / pcp2xlsx.py View on Github external
def write_xlsx(self, timestamp):
        """ Write results in XLSX format """
        if timestamp is None:
            # Complete and close
            self.wb.save(self.outfile)
            self.wb.close()
            self.wb = None
            return

        # Current row
        self.row += 1

        # Alignments
        left = openpyxl.styles.Alignment(horizontal="left")
        right = openpyxl.styles.Alignment(horizontal="right")

        def cell_str(col, row):
            """ Helper to return cell string """
            return chr(col) + str(row)

        def write_cell(col, row, value=None, bold=False, align=right):
            """ Write value to cell """
            if value is None:
                self.ws.cell(col, self.row)
                return
            if bold:
                self.ws[cell_str(col, row)].font = openpyxl.styles.Font(bold=True)
            self.ws[cell_str(col, self.row)].alignment = align
            self.ws[cell_str(col, self.row)] = value
github google / rekall / rekall / plugins / renderers / xls.py View on Github external
from openpyxl.styles import colors
from openpyxl.styles import fills

from rekall import utils
from rekall.ui import renderer
from rekall.ui import text

# pylint: disable=unexpected-keyword-arg,no-value-for-parameter
# pylint: disable=redefined-outer-name

HEADER_STYLE = styles.Style(font=styles.Font(bold=True))
SECTION_STYLE = styles.Style(
    fill=styles.PatternFill(
        fill_type=fills.FILL_SOLID, start_color=styles.Color(colors.RED)))
FORMAT_STYLE = styles.Style(
    alignment=styles.Alignment(vertical="top", wrap_text=False))


class XLSObjectRenderer(renderer.ObjectRenderer):
    """By default the XLS renderer delegates to the text renderer."""
    renders_type = "object"
    renderers = ["XLSRenderer"]

    STYLE = None

    def _GetDelegateObjectRenderer(self, item):
        return self.ForTarget(item, "TextRenderer")(
            session=self.session, renderer=self.renderer.delegate_text_renderer)

    def RenderHeader(self, worksheet, column):
        cell = worksheet.cell(
            row=worksheet.current_row, column=worksheet.current_column)
github DSM-DMS / DMS-Backend / Server / utils / excel_style_manager.py View on Github external
def ready_uuid_worksheet(ws):
    for row in range(1, 23):
        # 1 to 22
        for col in range(65, 68):
            cell = ws[chr(col) + str(row)]

            cell.alignment = Alignment(horizontal='center')
            cell.font = Font(bold=True)

    ws['A1'] = '학번'
    ws['B1'] = '이름'
    ws['C1'] = 'Code'
github appcell / OverwatchDataAnalysis / ora / excel / sheet3.py View on Github external
def _set_cell_style(cell, font2 = False):
        style = Config.cell_style
        if font2:
            cell.font = Font(**style['font2'])
        else:
            cell.font = Font(**style['font1'])
        cell.alignment = Alignment(**style['alignment'])
github BLKSerene / Wordless / src / wordless_widgets / wordless_table.py View on Github external
def style_cell_num(self, cell, item):
        cell.font = openpyxl.styles.Font(
            name = item.font().family(),
            size = 8,
            color = '292929'
        )

        cell.alignment = openpyxl.styles.Alignment(
            horizontal = 'right',
            vertical = 'center',
            wrap_text = True
        )