style.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from openpyxl.cell import cell
  15. from openpyxl.styles import (
  16. Font,
  17. Alignment,
  18. PatternFill,
  19. NamedStyle,
  20. Border,
  21. Side,
  22. Color,
  23. )
  24. from openpyxl.styles.fills import FILL_SOLID
  25. from openpyxl.styles.numbers import FORMAT_CURRENCY_USD_SIMPLE, FORMAT_PERCENTAGE
  26. from openpyxl.styles.colors import BLACK
  27. FORMAT_DATE_MMDDYYYY = "mm/dd/yyyy"
  28. def colormap(color):
  29. """
  30. Convenience for looking up known colors
  31. """
  32. cmap = {"black": BLACK}
  33. return cmap.get(color, color)
  34. def style_string_to_dict(style):
  35. """
  36. Convert css style string to a python dictionary
  37. """
  38. def clean_split(string, delim):
  39. """
  40. Clean up a string by removing all spaces and splitting on delim.
  41. """
  42. return (s.strip() for s in string.split(delim))
  43. styles = [clean_split(s, ":") for s in style.split(";") if ":" in s]
  44. return dict(styles)
  45. def get_side(style, name):
  46. """
  47. get side
  48. """
  49. return {
  50. "border_style": style.get("border-{}-style".format(name)),
  51. "color": colormap(style.get("border-{}-color".format(name))),
  52. }
  53. known_styles = {}
  54. def style_dict_to_named_style(style_dict, number_format=None):
  55. """
  56. Change css style (stored in a python dictionary) to openpyxl NamedStyle
  57. """
  58. style_and_format_string = str(
  59. {
  60. "style_dict": style_dict,
  61. "parent": style_dict.parent,
  62. "number_format": number_format,
  63. }
  64. )
  65. if style_and_format_string not in known_styles:
  66. # Font
  67. font = Font(
  68. bold=style_dict.get("font-weight") == "bold",
  69. color=style_dict.get_color("color", None),
  70. size=style_dict.get("font-size"),
  71. )
  72. # Alignment
  73. alignment = Alignment(
  74. horizontal=style_dict.get("text-align", "general"),
  75. vertical=style_dict.get("vertical-align"),
  76. wrap_text=style_dict.get("white-space", "nowrap") == "normal",
  77. )
  78. # Fill
  79. bg_color = style_dict.get_color("background-color")
  80. fg_color = style_dict.get_color("foreground-color", Color())
  81. fill_type = style_dict.get("fill-type")
  82. if bg_color and bg_color != "transparent":
  83. fill = PatternFill(
  84. fill_type=fill_type or FILL_SOLID,
  85. start_color=bg_color,
  86. end_color=fg_color,
  87. )
  88. else:
  89. fill = PatternFill()
  90. # Border
  91. border = Border(
  92. left=Side(**get_side(style_dict, "left")),
  93. right=Side(**get_side(style_dict, "right")),
  94. top=Side(**get_side(style_dict, "top")),
  95. bottom=Side(**get_side(style_dict, "bottom")),
  96. diagonal=Side(**get_side(style_dict, "diagonal")),
  97. diagonal_direction=None,
  98. outline=Side(**get_side(style_dict, "outline")),
  99. vertical=None,
  100. horizontal=None,
  101. )
  102. name = "Style {}".format(len(known_styles) + 1)
  103. pyxl_style = NamedStyle(
  104. name=name,
  105. font=font,
  106. fill=fill,
  107. alignment=alignment,
  108. border=border,
  109. number_format=number_format,
  110. )
  111. known_styles[style_and_format_string] = pyxl_style
  112. return known_styles[style_and_format_string]
  113. class StyleDict(dict):
  114. """
  115. It's like a dictionary, but it looks for items in the parent dictionary
  116. """
  117. def __init__(self, *args, **kwargs):
  118. self.parent = kwargs.pop("parent", None)
  119. super(StyleDict, self).__init__(*args, **kwargs)
  120. def __getitem__(self, item):
  121. if item in self:
  122. return super(StyleDict, self).__getitem__(item)
  123. elif self.parent:
  124. return self.parent[item]
  125. else:
  126. raise KeyError("{} not found".format(item))
  127. def __hash__(self):
  128. return hash(tuple([(k, self.get(k)) for k in self._keys()]))
  129. # Yielding the keys avoids creating unnecessary data structures
  130. # and happily works with both python2 and python3 where the
  131. # .keys() method is a dictionary_view in python3 and a list in python2.
  132. def _keys(self):
  133. yielded = set()
  134. for k in self.keys():
  135. yielded.add(k)
  136. yield k
  137. if self.parent:
  138. for k in self.parent._keys():
  139. if k not in yielded:
  140. yielded.add(k)
  141. yield k
  142. def get(self, k, d=None):
  143. try:
  144. return self[k]
  145. except KeyError:
  146. return d
  147. def get_color(self, k, d=None):
  148. """
  149. Strip leading # off colors if necessary
  150. """
  151. color = self.get(k, d)
  152. if hasattr(color, "startswith") and color.startswith("#"):
  153. color = color[1:]
  154. if (
  155. len(color) == 3
  156. ): # Premailers reduces colors like #00ff00 to #0f0, openpyxl doesn't like that
  157. color = "".join(2 * c for c in color)
  158. return color
  159. class Element(object):
  160. """
  161. Our base class for representing an html element along with a cascading style.
  162. The element is created along with a parent so that the StyleDict that we store
  163. can point to the parent's StyleDict.
  164. """
  165. def __init__(self, element, parent=None):
  166. self.element = element
  167. self.number_format = None
  168. parent_style = parent.style_dict if parent else None
  169. self.style_dict = StyleDict(
  170. style_string_to_dict(element.get("style", "")), parent=parent_style
  171. )
  172. self._style_cache = None
  173. def style(self):
  174. """
  175. Turn the css styles for this element into an openpyxl NamedStyle.
  176. """
  177. if not self._style_cache:
  178. self._style_cache = style_dict_to_named_style(
  179. self.style_dict, number_format=self.number_format
  180. )
  181. return self._style_cache
  182. def get_dimension(self, dimension_key):
  183. """
  184. Extracts the dimension from the style dict of the Element and returns it as a float.
  185. """
  186. dimension = self.style_dict.get(dimension_key)
  187. if dimension:
  188. if dimension[-2:] in ["px", "em", "pt", "in", "cm"]:
  189. dimension = dimension[:-2]
  190. dimension = float(dimension)
  191. return dimension
  192. class Table(Element):
  193. """
  194. The concrete implementations of Elements are semantically named for the types of elements we are interested in.
  195. This defines a very concrete tree structure for html tables that we expect to deal with. I prefer this compared to
  196. allowing Element to have an arbitrary number of children and dealing with an abstract element tree.
  197. """
  198. def __init__(self, table):
  199. """
  200. takes an html table object (from lxml)
  201. """
  202. super(Table, self).__init__(table)
  203. table_head = table.find("thead")
  204. self.head = (
  205. TableHead(table_head, parent=self) if table_head is not None else None
  206. )
  207. table_body = table.find("tbody")
  208. self.body = TableBody(
  209. table_body if table_body is not None else table, parent=self
  210. )
  211. class TableHead(Element):
  212. """
  213. This class maps to the `<th>` element of the html table.
  214. """
  215. def __init__(self, head, parent=None):
  216. super(TableHead, self).__init__(head, parent=parent)
  217. self.rows = [TableRow(tr, parent=self) for tr in head.findall("tr")]
  218. class TableBody(Element):
  219. """
  220. This class maps to the `<tbody>` element of the html table.
  221. """
  222. def __init__(self, body, parent=None):
  223. super(TableBody, self).__init__(body, parent=parent)
  224. self.rows = [TableRow(tr, parent=self) for tr in body.findall("tr")]
  225. class TableRow(Element):
  226. """
  227. This class maps to the `<tr>` element of the html table.
  228. """
  229. def __init__(self, tr, parent=None):
  230. super(TableRow, self).__init__(tr, parent=parent)
  231. self.cells = [
  232. TableCell(cell, parent=self) for cell in tr.findall("th") + tr.findall("td")
  233. ]
  234. def element_to_string(el):
  235. """
  236. element to string
  237. """
  238. return _element_to_string(el).strip()
  239. def _element_to_string(el):
  240. """
  241. element to string
  242. """
  243. string = ""
  244. for x in el.iterchildren():
  245. string += "\n" + _element_to_string(x)
  246. text = el.text.strip() if el.text else ""
  247. tail = el.tail.strip() if el.tail else ""
  248. return text + string + "\n" + tail
  249. class TableCell(Element):
  250. """
  251. This class maps to the `<td>` element of the html table.
  252. """
  253. CELL_TYPES = {
  254. "TYPE_STRING",
  255. "TYPE_FORMULA",
  256. "TYPE_NUMERIC",
  257. "TYPE_BOOL",
  258. "TYPE_CURRENCY",
  259. "TYPE_PERCENTAGE",
  260. "TYPE_NULL",
  261. "TYPE_INLINE",
  262. "TYPE_ERROR",
  263. "TYPE_FORMULA_CACHE_STRING",
  264. "TYPE_INTEGER",
  265. }
  266. def __init__(self, cell, parent=None):
  267. super(TableCell, self).__init__(cell, parent=parent)
  268. self.value = element_to_string(cell)
  269. self.number_format = self.get_number_format()
  270. def data_type(self):
  271. """
  272. get data type
  273. """
  274. cell_types = self.CELL_TYPES & set(self.element.get("class", "").split())
  275. if cell_types:
  276. if "TYPE_FORMULA" in cell_types:
  277. # Make sure TYPE_FORMULA takes precedence over the other classes in the set.
  278. cell_type = "TYPE_FORMULA"
  279. elif cell_types & {"TYPE_CURRENCY", "TYPE_INTEGER", "TYPE_PERCENTAGE"}:
  280. cell_type = "TYPE_NUMERIC"
  281. else:
  282. cell_type = cell_types.pop()
  283. else:
  284. cell_type = "TYPE_STRING"
  285. return getattr(cell, cell_type)
  286. def get_number_format(self):
  287. """
  288. get number format
  289. """
  290. if "TYPE_CURRENCY" in self.element.get("class", "").split():
  291. return FORMAT_CURRENCY_USD_SIMPLE
  292. if "TYPE_INTEGER" in self.element.get("class", "").split():
  293. return "#,##0"
  294. if "TYPE_PERCENTAGE" in self.element.get("class", "").split():
  295. return FORMAT_PERCENTAGE
  296. if "TYPE_DATE" in self.element.get("class", "").split():
  297. return FORMAT_DATE_MMDDYYYY
  298. if self.data_type() == cell.TYPE_NUMERIC:
  299. try:
  300. int(self.value)
  301. except ValueError:
  302. return "#,##0.##"
  303. else:
  304. return "#,##0"
  305. def format(self, cell):
  306. """
  307. format
  308. """
  309. cell.style = self.style()
  310. data_type = self.data_type()
  311. if data_type:
  312. cell.data_type = data_type