How to use the openpyxl.styles.Font 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 scuml / django-datatables / src / django_datatables / excel.py View on Github external
def _create_sheets(self):
        """
        Creates sheets in workbook using current sheets data
        """
        header_style = Style(Font(bold=True))

        for sheet_name, data in self.sheets.items():
            sheet = self.workbook.create_sheet(title=sheet_name)

            header_row = list()
            for header in data['headers']:
                header_row.append(dict(
                    value=header,
                    style=header_style,
                ))
            sheet.append(header_row)
            row_num = 1

            for rec in iter(data["data"]):
                if rec is None:
                    continue
github DeepSpace2 / StyleFrame / StyleFrame / styler.py View on Github external
def to_openpyxl_style(self):
        try:
            openpyxl_style = self.cache[self]
        except KeyError:
            side = Side(border_style=self.border_type, color=utils.colors.black)
            border = Border(left=side, right=side, top=side, bottom=side)
            openpyxl_style = self.cache[self] = NamedStyle(
                name=str(hash(self)),
                font=Font(name=self.font, size=self.font_size, color=OpenPyColor(self.font_color),
                          bold=self.bold, underline=self.underline),
                fill=PatternFill(patternType=self.fill_pattern_type, fgColor=self.bg_color),
                alignment=Alignment(horizontal=self.horizontal_alignment, vertical=self.vertical_alignment,
                                    wrap_text=self.wrap_text, shrink_to_fit=self.shrink_to_fit,
                                    indent=self.indent, text_rotation=self.text_rotation),
                border=border,
                number_format=self.number_format,
                protection=Protection(locked=self.protection)
            )
        return openpyxl_style
github jjgomera / pychemqt / lib / utilities.py View on Github external
if title:
            for i, ttl in enumerate(header):
                sheet.write(0, i, ttl, style)
        for j, row in enumerate(matrix):
            for i, data in enumerate(row):
                sheet.write(j+1, i, data)
        spreadsheet.save(fname)

    elif ext == "xlsx":
        import openpyxl
        from openpyxl.styles import Font
        spreadsheet = openpyxl.Workbook()
        sheet = spreadsheet.active
        sheet.title = sheetTitle

        font1 = Font()
        font1.size = 9
        font1.bold = True
        font2 = Font()
        font2.size = 9

        # Add Data
        if title:
            for i, ttl in enumerate(header):
                sheet["%s%i" % (spreadsheetColumn(i), 1)] = ttl
                sheet["%s%i" % (spreadsheetColumn(i), 1)].style.font = font1
        for j, row in enumerate(matrix):
            for i, data in enumerate(row):
                sheet["%s%i" % (spreadsheetColumn(i), j+2)] = data
                sheet["%s%i" % (spreadsheetColumn(i), j+2)].style.font = font2
        spreadsheet.save(filename=fname)
github TheKnightCoder / Ansible-Networking / lib / modules / poe_devices.py View on Github external
def WriteDictToXl(file_path, hostname, data):
  
  bold = Font(bold=True)
  file_exists = os.path.isfile(file_path)
  if file_exists:
    wb = load_workbook(file_path)
    ws = wb.create_sheet(hostname)
  else:
    wb = Workbook()
    ws = wb.active
    ws.title = hostname
    
  for i in range(0,len(data[0])): #adding column headers
    cell=ws.cell(row=1, column=i+1, value=data[0].keys()[i])
    cell.font = bold
 
  greenFill = PatternFill(fill_type='solid', start_color='c6efce', end_color='c6efce')
  for item in data:
    cur_row = ws.max_row+1
github yidao620c / core-python / samples / excel / generate_schema.py View on Github external
def write_dest(xlsx_name, schema_name):
    border = Border(
        left=Side(border_style=borders.BORDER_THIN, color='FF000000'),
        right=Side(border_style=borders.BORDER_THIN, color='FF000000'),
        top=Side(border_style=borders.BORDER_THIN, color='FF000000'),
        bottom=Side(border_style=borders.BORDER_THIN, color='FF000000')
    )
    alignment = Alignment(horizontal='justify', vertical='bottom',
                          text_rotation=0, wrap_text=False,
                          shrink_to_fit=True, indent=0)
    fill = PatternFill(fill_type=None, start_color='FFFFFFFF')
    # 基本的样式
    basic_style = NamedStyle(name="basic_style", font=Font(name='Microsoft YaHei')
                             , border=border, alignment=alignment, fill=fill)
    title_style = copy(basic_style)
    title_style.name = 'title_style'
    title_style.font = Font(name='Microsoft YaHei', b=True, size=20, color='00215757')
    title_style.alignment = Alignment(horizontal='center', vertical='bottom',
                                      text_rotation=0, wrap_text=False,
                                      shrink_to_fit=True, indent=0)
    title_style.fill = PatternFill(fill_type=fills.FILL_SOLID, start_color='00B2CBED')
    header_style = copy(basic_style)
    header_style.name='header_style'
    header_style.font = Font(name='Microsoft YaHei', b=True, size=15, color='00215757')
    header_style.fill = PatternFill(fill_type=fills.FILL_SOLID, start_color='00BAA87F')
    common_style = copy(basic_style)
    common_style.name = 'common_style'
    link_style = copy(basic_style)
    link_style.name = 'link_style'
github bcgov / gwells / app / backend / wells / management / commands / export.py View on Github external
worksheet = workbook.create_sheet(worksheet_name)
        csv_file = '{}.csv'.format(worksheet_name)
        # If any of the export files already exist, delete them
        if os.path.exists(csv_file):
            os.remove(csv_file)
        with open(csv_file, 'w') as csvfile:
            csvwriter = csv.writer(csvfile, dialect='excel')

            values = []
            cells = []
            # Write the headings
            for index, field in enumerate(cursor.description):
                fieldName = field[0]
                values.append(fieldName)
                cell = WriteOnlyCell(worksheet, value=fieldName)
                cell.font = Font(bold=True)
                cells.append(cell)
            columns = len(values)

            for index, value in enumerate(values):
                worksheet.column_dimensions[get_column_letter(index+1)].width = len(value) + 2

            worksheet.append(cells)
            csvwriter.writerow(values)

            # Write the values
            row_index = 0
            for row, record in enumerate(ResultIter(cursor)):
                values = []
                num_values = 0
                for col, value in enumerate(record):
                    if not (value == "" or value is None):
github bcgov / gwells / app / backend / wells / renderers.py View on Github external
def write_headers(self, headers):
        self.headers = headers

        header_cells = []
        for index, header_key in enumerate(self.headers, 1):
            label = COLUMN_LABELS.get(header_key)

            column = openpyxl.utils.get_column_letter(index)
            width = (len(label) + 2) * 1.2
            self.sheet.column_dimensions[column].width = width

            cell = openpyxl.cell.WriteOnlyCell(self.sheet, value=label)
            cell.font = openpyxl.styles.Font(bold=True)
            header_cells.append(cell)

        self.sheet.append(header_cells)
github actionml / ur-analysis-tools / excel.py View on Github external
def create_table(ws, column_names, columns, title=None, bold_first_column=True, selected_rows=None, selected_columns=None):
    if selected_rows is None:
        selected_rows = []

    if selected_columns is None:
        selected_columns = []

    bold_ft = Font(bold=True)
    fill = PatternFill(fill_type='solid',
                       start_color='FF27E85B',
                       end_color='FF27E85B')

    #prepare data
    formated_columns = []
    for column in columns:
        formated_column = []
        for value in column:
            if isinstance(value, int):
                formated_column.append("{:,}".format(value))
            elif isinstance(value, float):
                formated_column.append("%.4f" % value)
            else:
                formated_column.append(value)
        formated_columns.append(formated_column)
github google / rekall / rekall / plugins / renderers / xls.py View on Github external
"""
import time
import openpyxl

from openpyxl import styles
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")(
github Dynatrace / dynatrace-api / ExcelExport / dt-excel.py View on Github external
wsFWRules.merge_cells('O1:R1')
wsFWRules.append([ 'fromProcessId','toProcessId','fromHostId','toHostId','',
	'srcIP','dstIP','proto','port','',
	'srcHostName','srcProcessName','srcProcessType','',
	'dstHostname','dstProcessName','dstProcessType','',
	'isIntraHost?'
	])
for col in ['A','B','C','D','E']:
	wsFWRules.column_dimensions[col].hidden=True
wsFWRules["A1"].style="Accent3"
wsFWRules["F1"].style="Accent1"
wsFWRules["K1"].style="Accent4"
wsFWRules["O1"].style="Accent5"
wsFWRules["S1"].style="Accent2"
for cell in wsFWRules["1:1"]:
	cell.font=Font(bold=True,color='FFFFFF')
	cell.alignment=Alignment(horizontal='center')
for cell in wsFWRules["2:2"]:
	cell.style='Headline 3'
wsFWRules.sheet_properties.tabColor = '0066FF'

i=3
for row in wsProcessProcess.rows:
	wsFWRules.append([
		"='process-process'!A%i" % i,
		"='process-process'!B%i" % i,
		"=VLOOKUP(A%i,'process-host'!$A:$B,2,FALSE)" % i,
		"=VLOOKUP(B%i,'process-host'!$A:$B,2,FALSE)" % i,
		"",
		"=VLOOKUP(C%i,'hosts'!$A:$F,6,FALSE)" % i,
		"=VLOOKUP(D%i,'hosts'!$A:$F,6,FALSE)" % i,
		"TCP",