BonPrinter v1.2.0
Thermal Printer tool
Loading...
Searching...
No Matches
openpyxl_util.py
Go to the documentation of this file.
1"""!
2********************************************************************************
3@file openpyxl_util.py
4@brief Util function for openpyxl
5********************************************************************************
6"""
7
8from typing import Optional
9from datetime import datetime, time
10from openpyxl import Workbook
11from openpyxl.utils import get_column_letter
12from openpyxl.worksheet import table
13from openpyxl.worksheet.worksheet import Worksheet
14from openpyxl.styles import Font, PatternFill, Alignment
15from openpyxl.styles.borders import Border, Side
16
17FONT_SIZE = 11
18FONT_NAME = "Calibri"
19MAX_COLUMN_WIDTH = 30
20MAX_ROW_HEIGHT = 1.3
21
22# https://www.farb-tabelle.de/de/farbtabelle.htm
23COLOR_BLACK = "000000"
24COLOR_BLUE = "0000FF"
25COLOR_BROWN = "A52A2A"
26COLOR_GREY = "BEBEBE"
27COLOR_GREEN = "00FF00"
28COLOR_ORANGE = "FFA500"
29COLOR_RED = "FF0000"
30COLOR_VIOLET = "EE82EE"
31COLOR_WHITE = "FFFFFF"
32COLOR_YELLOW = "FFFF00"
33
34THIN_BORDER = Border(left=Side(style="thin"),
35 right=Side(style="thin"),
36 top=Side(style="thin"),
37 bottom=Side(style="thin"))
38
39NUMBER_FORMAT_CURRENCY = "#,##0.00"
40NUMBER_FORMAT_EUR = "#,##0.00 €"
41NUMBER_FORMAT_PERCENT = "0%"
42NUMBER_FORMAT_DATETIME = "YYYY-MM-DD HH:MM:SS"
43NUMBER_FORMAT_TIME = "hh:mm"
44
45PAGE_MARGIN_FACTOR = 1 / 2.54 # convert inch to cm
46
47
49 """!
50 @brief XLS file creator
51 @param font_name : default font name
52 @param font_size : default font size
53 """
54
55 def __init__(self, font_name: Optional[str] = None, font_size: Optional[int] = None):
56 self.font_name = FONT_NAME if (font_name is None) else font_name
57 self.font_size = FONT_SIZE if (font_size is None) else font_size
58 self.workbook = Workbook()
59
60 def save(self, filename: str) -> None:
61 """!
62 @brief Save file
63 @param filename : name of file
64 """
65 self.workbook.save(filename=filename)
66
67 def set_table(self, worksheet: Worksheet, max_col: int, max_row: int, min_col: int = 1, min_row: int = 1) -> None:
68 """!
69 @brief Set table
70 @param worksheet : worksheet
71 @param max_col : maximum column
72 @param max_row : maximum row
73 @param min_col : minimum column (default is first column)
74 @param min_row : worksheet (default is first row)
75 """
76 table_style = table.TableStyleInfo(name="TableStyleLight15",
77 showRowStripes=True)
78 start_cell = get_column_letter(min_col) + str(min_row)
79 end_cell = get_column_letter(max_col) + str(max_row)
80 new_table = table.Table(ref=f"{start_cell}:{end_cell}",
81 displayName=worksheet.title,
82 tableStyleInfo=table_style)
83 worksheet.add_table(new_table)
84
85 def set_page_marcins(self, worksheet: Worksheet, left: Optional[float] = None, right: Optional[float] = None,
86 top: Optional[float] = None, bottom: Optional[float] = None) -> None:
87 """!
88 @brief Set page margins in cm
89 @param worksheet : select worksheet
90 @param left : left margin in cm
91 @param right : left margin in cm
92 @param top : left margin in cm
93 @param bottom : left margin in cm
94 """
95 if left is not None:
96 worksheet.page_margins.left = left * PAGE_MARGIN_FACTOR
97 if right is not None:
98 worksheet.page_margins.right = right * PAGE_MARGIN_FACTOR
99 if top is not None:
100 worksheet.page_margins.top = top * PAGE_MARGIN_FACTOR
101 if bottom is not None:
102 worksheet.page_margins.bottom = bottom * PAGE_MARGIN_FACTOR
103
104 def set_column_autowidth(self, worksheet: Worksheet, b_limit: bool = True) -> None:
105 """!
106 @brief Set automatic column width of worksheet.
107 @param worksheet : select worksheet
108 @param b_limit : status if width has a max limit
109 """
110 for i, col_cells in enumerate(worksheet.columns, start=1):
111 i_max_col_len = 0
112 for j, cell in enumerate(col_cells):
113 if b_limit:
114 if j != 0: # do use not use first line description
115 i_max_col_len = max(i_max_col_len, len(str(cell.value).split("n", maxsplit=1)[0]))
116 else:
117 for s_line in str(cell.value).split("/n"):
118 i_max_col_len = max(i_max_col_len, len(s_line))
119 if b_limit:
120 i_max_col_len = min(i_max_col_len, MAX_COLUMN_WIDTH)
121 if i_max_col_len == 0:
122 worksheet.column_dimensions[get_column_letter(i)].hidden = True # hide empty lines
123 else:
124 worksheet.column_dimensions[get_column_letter(i)].width = (i_max_col_len + 1) * 0.10 * self.font_size
125
126 def set_row_autoheight(self, worksheet: Worksheet, b_limit: bool = True) -> None:
127 """!
128 @brief Set automatic row height of worksheet.
129 @param worksheet : select worksheet
130 @param b_limit : status if height has a max limit
131 """
132 for i, col_cells in enumerate(worksheet.rows, start=1):
133 i_high = MAX_ROW_HEIGHT
134 if not b_limit:
135 for cell in col_cells:
136 i_high = max(i_high, len(str(cell.value).split("\n")) * MAX_ROW_HEIGHT)
137 worksheet.row_dimensions[i].height = i_high * self.font_size
138
139 def set_cell(self, ws: Worksheet, row: int, column: int, value: Optional[str | int | float | datetime | time] = None,
140 font_name: Optional[str] = None, color: Optional[str] = None, font_size: Optional[int] = None,
141 bold: bool = False, italic: bool = False, strike: bool = False, underline: Optional[str] = None,
142 vert_align: Optional[str] = None, fill_color: Optional[str] = None,
143 align: Optional[str] = None, align_vert: Optional[str] = "center", wrap_text: bool = False,
144 number_format: Optional[str] = None, border: Optional[Border] = None) -> None:
145 """!
146 @brief Set cell data
147 Font: https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.fonts.html
148 PatternFill: https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles.fills.html#openpyxl.styles.fills.PatternFill
149 Alignment: https://openpyxl.readthedocs.io/en/latest/api/openpyxl.styles.alignment.html
150 @param ws : worksheet
151 @param row : row position
152 @param column : column position
153 @param value : cell value [numeric, time, string, bool, None]
154 @param font_name : font name (default is Calibri)
155 @param color : font color e.g. "FF0000" for red
156 @param font_size : font size
157 @param bold : status if cell content should be bold
158 @param italic : status if cell content should be italic
159 @param strike : strike option
160 @param underline : underline options ['double', 'doubleAccounting', 'single', 'singleAccounting']
161 @param vert_align : vertical align options ['superscript', 'subscript', 'baseline']
162 @param fill_color : background fill color of cell
163 @param align : horizontal text align option ["general", "left", "center", "right", "fill", "justify", "centerContinuous", "distributed"]
164 @param align_vert : vertical text align of cell ["top", "center", "bottom", "justify", "distributed"]
165 @param wrap_text : wrap text
166 @param number_format : number format of cell
167 @param border : border of cell
168 """
169 if font_name is None:
170 font_name = self.font_name
171 if font_size is None:
172 font_size = self.font_size
173 cell = ws.cell(row=row, column=column, value=value)
174 cell.font = Font(name=font_name, color=color, size=str(font_size), bold=bold, italic=italic,
175 strikethrough=strike, underline=underline, vertAlign=vert_align)
176 if fill_color is not None:
177 cell.fill = PatternFill(fill_type="solid", start_color=fill_color, end_color=fill_color)
178 cell.alignment = Alignment(horizontal=align, vertical=align_vert, wrap_text=wrap_text)
179 if number_format is not None:
180 cell.number_format = number_format
181 if border is not None:
182 cell.border = border
None set_table(self, Worksheet worksheet, int max_col, int max_row, int min_col=1, int min_row=1)
Set table.
__init__(self, Optional[str] font_name=None, Optional[int] font_size=None)
None set_cell(self, Worksheet ws, int row, int column, Optional[str|int|float|datetime|time] value=None, Optional[str] font_name=None, Optional[str] color=None, Optional[int] font_size=None, bool bold=False, bool italic=False, bool strike=False, Optional[str] underline=None, Optional[str] vert_align=None, Optional[str] fill_color=None, Optional[str] align=None, Optional[str] align_vert="center", bool wrap_text=False, Optional[str] number_format=None, Optional[Border] border=None)
Set cell data Font: https://openpyxl.readthedocs.io/en/stable/api/openpyxl.styles....
None save(self, str filename)
Save file.
None set_column_autowidth(self, Worksheet worksheet, bool b_limit=True)
Set automatic column width of worksheet.
None set_page_marcins(self, Worksheet worksheet, Optional[float] left=None, Optional[float] right=None, Optional[float] top=None, Optional[float] bottom=None)
Set page margins in cm.
None set_row_autoheight(self, Worksheet worksheet, bool b_limit=True)
Set automatic row height of worksheet.