@v587d/capital-generation 2.29.0 → 2.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (299) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +16 -0
  4. package/automation/package.json +1 -1
  5. package/chart-ui/package.json +1 -1
  6. package/config/package.json +1 -1
  7. package/lib/collector-runtime.js +56 -1
  8. package/lib/data-collector/catalog-taxonomy.d.ts +1 -1
  9. package/lib/data-collector/catalog-taxonomy.js +33 -0
  10. package/lib/data-collector/tools.js +7 -7
  11. package/lib/python-runtime/errors.d.ts +1 -1
  12. package/lib/python-runtime/errors.js +2 -0
  13. package/lib/python-runtime/manager.d.ts +28 -1
  14. package/lib/python-runtime/manager.js +141 -5
  15. package/lib/python-runtime/probe.d.ts +24 -0
  16. package/lib/python-runtime/probe.js +66 -50
  17. package/lib/sources/csindex-http.d.ts +4 -0
  18. package/lib/sources/csindex-http.js +233 -0
  19. package/lib/sources/eastmoney-http.js +1504 -1
  20. package/lib/sources/fuyao-rest.js +168 -8
  21. package/lib/sources/official-http.d.ts +4 -0
  22. package/lib/sources/official-http.js +477 -0
  23. package/lib/sources/python-remote.d.ts +25 -0
  24. package/lib/sources/python-remote.js +461 -0
  25. package/lib/sources/sina-http.d.ts +2 -0
  26. package/lib/sources/sina-http.js +484 -0
  27. package/lib/sources/tencent-http.js +23 -8
  28. package/lib/sources/ths-http.d.ts +2 -0
  29. package/lib/sources/ths-http.js +514 -0
  30. package/lib/time/tools.js +19 -0
  31. package/lib/web-retriever/local-fetch.d.ts +1 -1
  32. package/lib/web-retriever/local-fetch.js +1 -1
  33. package/lib/web-retriever/sources.d.ts +7 -0
  34. package/lib/web-retriever/sources.js +46 -21
  35. package/lib/web-retriever/throttle.d.ts +8 -0
  36. package/lib/web-retriever/throttle.js +13 -0
  37. package/lib/web-retriever/tools.js +1 -1
  38. package/lib/web-retriever/wind-client.d.ts +1 -1
  39. package/lib/web-retriever/wind-client.js +1 -1
  40. package/package.json +1 -1
  41. package/preset/capital-generation/agent.patch.yml +7 -5
  42. package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +16 -16
  43. package/python/scripts/baostock_stock_basic.py +129 -0
  44. package/python/scripts/baostock_valuation_history.py +141 -0
  45. package/python/scripts/pbc_social_financing.py +291 -0
  46. package/python/vendor/baostock/LICENSE +19 -0
  47. package/python/vendor/baostock/__init__.py +42 -0
  48. package/python/vendor/baostock/common/__init__.py +0 -0
  49. package/python/vendor/baostock/common/contants.py +189 -0
  50. package/python/vendor/baostock/common/context.py +4 -0
  51. package/python/vendor/baostock/corpreport/__init__.py +0 -0
  52. package/python/vendor/baostock/corpreport/corp_performance.py +202 -0
  53. package/python/vendor/baostock/data/__init__.py +0 -0
  54. package/python/vendor/baostock/data/messageheader.py +17 -0
  55. package/python/vendor/baostock/data/msg.py +21 -0
  56. package/python/vendor/baostock/data/resultset.py +200 -0
  57. package/python/vendor/baostock/demo/__init__.py +0 -0
  58. package/python/vendor/baostock/demo/demo_A_stock_5mk-data.py +34 -0
  59. package/python/vendor/baostock/demo/demo_A_stock_k_data.py +36 -0
  60. package/python/vendor/baostock/demo/demo_AllStock.py +27 -0
  61. package/python/vendor/baostock/demo/demo_Balance_data.py +22 -0
  62. package/python/vendor/baostock/demo/demo_CashFlow_data.py +22 -0
  63. package/python/vendor/baostock/demo/demo_Dividend_data.py +35 -0
  64. package/python/vendor/baostock/demo/demo_Dupont_data.py +25 -0
  65. package/python/vendor/baostock/demo/demo_Forecast_report.py +24 -0
  66. package/python/vendor/baostock/demo/demo_Growth_data.py +22 -0
  67. package/python/vendor/baostock/demo/demo_Index_k_data.py +39 -0
  68. package/python/vendor/baostock/demo/demo_Operation_data.py +22 -0
  69. package/python/vendor/baostock/demo/demo_PerformanceExpress_report.py +25 -0
  70. package/python/vendor/baostock/demo/demo_Profit_data.py +22 -0
  71. package/python/vendor/baostock/demo/demo_TradeDates.py +27 -0
  72. package/python/vendor/baostock/demo/demo_adjust_factor_data.py +23 -0
  73. package/python/vendor/baostock/demo/demo_assignDayData.py +23 -0
  74. package/python/vendor/baostock/demo/demo_daily_adjust_factor_data.py +28 -0
  75. package/python/vendor/baostock/demo/demo_daily_k_4_AStock.py +28 -0
  76. package/python/vendor/baostock/demo/demo_daily_k_4_ETF.py +28 -0
  77. package/python/vendor/baostock/demo/demo_depositRate_data.py +26 -0
  78. package/python/vendor/baostock/demo/demo_hs300_stocks.py +26 -0
  79. package/python/vendor/baostock/demo/demo_loanRate_data.py +26 -0
  80. package/python/vendor/baostock/demo/demo_moneySupplyDataMonth_data.py +26 -0
  81. package/python/vendor/baostock/demo/demo_moneySupplyDataYear_data.py +26 -0
  82. package/python/vendor/baostock/demo/demo_requiredReserveRatio_data.py +26 -0
  83. package/python/vendor/baostock/demo/demo_set_API_key.py +37 -0
  84. package/python/vendor/baostock/demo/demo_stockBasic_data.py +27 -0
  85. package/python/vendor/baostock/demo/demo_stock_Valuation_indicator_data.py +34 -0
  86. package/python/vendor/baostock/demo/demo_stock_industry.py +26 -0
  87. package/python/vendor/baostock/demo/demo_sz50stocks.py +26 -0
  88. package/python/vendor/baostock/demo/demo_zz500_stock.py +26 -0
  89. package/python/vendor/baostock/evaluation/__init__.py +0 -0
  90. package/python/vendor/baostock/evaluation/season_index.py +758 -0
  91. package/python/vendor/baostock/login/__init__.py +0 -0
  92. package/python/vendor/baostock/login/loginout.py +230 -0
  93. package/python/vendor/baostock/macroscopic/__init__.py +0 -0
  94. package/python/vendor/baostock/macroscopic/economic_data.py +723 -0
  95. package/python/vendor/baostock/metadata/__init__.py +0 -0
  96. package/python/vendor/baostock/metadata/stock_metadata.py +207 -0
  97. package/python/vendor/baostock/security/__init__.py +0 -0
  98. package/python/vendor/baostock/security/history.py +265 -0
  99. package/python/vendor/baostock/security/sectorinfo.py +1024 -0
  100. package/python/vendor/baostock/util/__init__.py +0 -0
  101. package/python/vendor/baostock/util/socketutil.py +97 -0
  102. package/python/vendor/baostock/util/stringutil.py +83 -0
  103. package/python/vendor/et_xmlfile/LICENSE +23 -0
  104. package/python/vendor/et_xmlfile/LICENSE.python +298 -0
  105. package/python/vendor/et_xmlfile/__init__.py +8 -0
  106. package/python/vendor/et_xmlfile/incremental_tree.py +917 -0
  107. package/python/vendor/et_xmlfile/xmlfile.py +158 -0
  108. package/python/vendor/openpyxl/LICENSE +23 -0
  109. package/python/vendor/openpyxl/__init__.py +19 -0
  110. package/python/vendor/openpyxl/_constants.py +13 -0
  111. package/python/vendor/openpyxl/cell/__init__.py +4 -0
  112. package/python/vendor/openpyxl/cell/_writer.py +136 -0
  113. package/python/vendor/openpyxl/cell/cell.py +332 -0
  114. package/python/vendor/openpyxl/cell/read_only.py +136 -0
  115. package/python/vendor/openpyxl/cell/rich_text.py +202 -0
  116. package/python/vendor/openpyxl/cell/text.py +184 -0
  117. package/python/vendor/openpyxl/chart/_3d.py +105 -0
  118. package/python/vendor/openpyxl/chart/__init__.py +19 -0
  119. package/python/vendor/openpyxl/chart/_chart.py +199 -0
  120. package/python/vendor/openpyxl/chart/area_chart.py +106 -0
  121. package/python/vendor/openpyxl/chart/axis.py +401 -0
  122. package/python/vendor/openpyxl/chart/bar_chart.py +144 -0
  123. package/python/vendor/openpyxl/chart/bubble_chart.py +67 -0
  124. package/python/vendor/openpyxl/chart/chartspace.py +195 -0
  125. package/python/vendor/openpyxl/chart/data_source.py +246 -0
  126. package/python/vendor/openpyxl/chart/descriptors.py +43 -0
  127. package/python/vendor/openpyxl/chart/error_bar.py +62 -0
  128. package/python/vendor/openpyxl/chart/label.py +127 -0
  129. package/python/vendor/openpyxl/chart/layout.py +74 -0
  130. package/python/vendor/openpyxl/chart/legend.py +75 -0
  131. package/python/vendor/openpyxl/chart/line_chart.py +129 -0
  132. package/python/vendor/openpyxl/chart/marker.py +90 -0
  133. package/python/vendor/openpyxl/chart/picture.py +35 -0
  134. package/python/vendor/openpyxl/chart/pie_chart.py +177 -0
  135. package/python/vendor/openpyxl/chart/pivot.py +65 -0
  136. package/python/vendor/openpyxl/chart/plotarea.py +162 -0
  137. package/python/vendor/openpyxl/chart/print_settings.py +57 -0
  138. package/python/vendor/openpyxl/chart/radar_chart.py +55 -0
  139. package/python/vendor/openpyxl/chart/reader.py +32 -0
  140. package/python/vendor/openpyxl/chart/reference.py +124 -0
  141. package/python/vendor/openpyxl/chart/scatter_chart.py +53 -0
  142. package/python/vendor/openpyxl/chart/series.py +197 -0
  143. package/python/vendor/openpyxl/chart/series_factory.py +41 -0
  144. package/python/vendor/openpyxl/chart/shapes.py +89 -0
  145. package/python/vendor/openpyxl/chart/stock_chart.py +54 -0
  146. package/python/vendor/openpyxl/chart/surface_chart.py +119 -0
  147. package/python/vendor/openpyxl/chart/text.py +78 -0
  148. package/python/vendor/openpyxl/chart/title.py +76 -0
  149. package/python/vendor/openpyxl/chart/trendline.py +98 -0
  150. package/python/vendor/openpyxl/chart/updown_bars.py +31 -0
  151. package/python/vendor/openpyxl/chartsheet/__init__.py +3 -0
  152. package/python/vendor/openpyxl/chartsheet/chartsheet.py +107 -0
  153. package/python/vendor/openpyxl/chartsheet/custom.py +61 -0
  154. package/python/vendor/openpyxl/chartsheet/properties.py +28 -0
  155. package/python/vendor/openpyxl/chartsheet/protection.py +41 -0
  156. package/python/vendor/openpyxl/chartsheet/publish.py +58 -0
  157. package/python/vendor/openpyxl/chartsheet/relation.py +97 -0
  158. package/python/vendor/openpyxl/chartsheet/views.py +51 -0
  159. package/python/vendor/openpyxl/comments/__init__.py +4 -0
  160. package/python/vendor/openpyxl/comments/author.py +21 -0
  161. package/python/vendor/openpyxl/comments/comment_sheet.py +211 -0
  162. package/python/vendor/openpyxl/comments/comments.py +62 -0
  163. package/python/vendor/openpyxl/comments/shape_writer.py +112 -0
  164. package/python/vendor/openpyxl/compat/__init__.py +54 -0
  165. package/python/vendor/openpyxl/compat/abc.py +8 -0
  166. package/python/vendor/openpyxl/compat/numbers.py +43 -0
  167. package/python/vendor/openpyxl/compat/product.py +17 -0
  168. package/python/vendor/openpyxl/compat/singleton.py +40 -0
  169. package/python/vendor/openpyxl/compat/strings.py +25 -0
  170. package/python/vendor/openpyxl/descriptors/__init__.py +58 -0
  171. package/python/vendor/openpyxl/descriptors/base.py +272 -0
  172. package/python/vendor/openpyxl/descriptors/container.py +41 -0
  173. package/python/vendor/openpyxl/descriptors/excel.py +112 -0
  174. package/python/vendor/openpyxl/descriptors/namespace.py +12 -0
  175. package/python/vendor/openpyxl/descriptors/nested.py +129 -0
  176. package/python/vendor/openpyxl/descriptors/sequence.py +136 -0
  177. package/python/vendor/openpyxl/descriptors/serialisable.py +240 -0
  178. package/python/vendor/openpyxl/descriptors/slots.py +18 -0
  179. package/python/vendor/openpyxl/drawing/__init__.py +4 -0
  180. package/python/vendor/openpyxl/drawing/colors.py +435 -0
  181. package/python/vendor/openpyxl/drawing/connector.py +144 -0
  182. package/python/vendor/openpyxl/drawing/drawing.py +92 -0
  183. package/python/vendor/openpyxl/drawing/effect.py +407 -0
  184. package/python/vendor/openpyxl/drawing/fill.py +425 -0
  185. package/python/vendor/openpyxl/drawing/geometry.py +584 -0
  186. package/python/vendor/openpyxl/drawing/graphic.py +177 -0
  187. package/python/vendor/openpyxl/drawing/image.py +65 -0
  188. package/python/vendor/openpyxl/drawing/line.py +144 -0
  189. package/python/vendor/openpyxl/drawing/picture.py +144 -0
  190. package/python/vendor/openpyxl/drawing/properties.py +174 -0
  191. package/python/vendor/openpyxl/drawing/relation.py +17 -0
  192. package/python/vendor/openpyxl/drawing/spreadsheet_drawing.py +382 -0
  193. package/python/vendor/openpyxl/drawing/text.py +717 -0
  194. package/python/vendor/openpyxl/drawing/xdr.py +33 -0
  195. package/python/vendor/openpyxl/formatting/__init__.py +3 -0
  196. package/python/vendor/openpyxl/formatting/formatting.py +114 -0
  197. package/python/vendor/openpyxl/formatting/rule.py +291 -0
  198. package/python/vendor/openpyxl/formula/__init__.py +3 -0
  199. package/python/vendor/openpyxl/formula/tokenizer.py +446 -0
  200. package/python/vendor/openpyxl/formula/translate.py +166 -0
  201. package/python/vendor/openpyxl/packaging/__init__.py +3 -0
  202. package/python/vendor/openpyxl/packaging/core.py +115 -0
  203. package/python/vendor/openpyxl/packaging/custom.py +289 -0
  204. package/python/vendor/openpyxl/packaging/extended.py +137 -0
  205. package/python/vendor/openpyxl/packaging/interface.py +56 -0
  206. package/python/vendor/openpyxl/packaging/manifest.py +194 -0
  207. package/python/vendor/openpyxl/packaging/relationship.py +158 -0
  208. package/python/vendor/openpyxl/packaging/workbook.py +185 -0
  209. package/python/vendor/openpyxl/pivot/__init__.py +1 -0
  210. package/python/vendor/openpyxl/pivot/cache.py +965 -0
  211. package/python/vendor/openpyxl/pivot/fields.py +326 -0
  212. package/python/vendor/openpyxl/pivot/record.py +111 -0
  213. package/python/vendor/openpyxl/pivot/table.py +1261 -0
  214. package/python/vendor/openpyxl/reader/__init__.py +1 -0
  215. package/python/vendor/openpyxl/reader/drawings.py +71 -0
  216. package/python/vendor/openpyxl/reader/excel.py +349 -0
  217. package/python/vendor/openpyxl/reader/strings.py +44 -0
  218. package/python/vendor/openpyxl/reader/workbook.py +133 -0
  219. package/python/vendor/openpyxl/styles/__init__.py +11 -0
  220. package/python/vendor/openpyxl/styles/alignment.py +62 -0
  221. package/python/vendor/openpyxl/styles/borders.py +103 -0
  222. package/python/vendor/openpyxl/styles/builtins.py +1397 -0
  223. package/python/vendor/openpyxl/styles/cell_style.py +206 -0
  224. package/python/vendor/openpyxl/styles/colors.py +172 -0
  225. package/python/vendor/openpyxl/styles/differential.py +95 -0
  226. package/python/vendor/openpyxl/styles/fills.py +224 -0
  227. package/python/vendor/openpyxl/styles/fonts.py +113 -0
  228. package/python/vendor/openpyxl/styles/named_styles.py +282 -0
  229. package/python/vendor/openpyxl/styles/numbers.py +200 -0
  230. package/python/vendor/openpyxl/styles/protection.py +17 -0
  231. package/python/vendor/openpyxl/styles/proxy.py +62 -0
  232. package/python/vendor/openpyxl/styles/styleable.py +151 -0
  233. package/python/vendor/openpyxl/styles/stylesheet.py +274 -0
  234. package/python/vendor/openpyxl/styles/table.py +94 -0
  235. package/python/vendor/openpyxl/utils/__init__.py +17 -0
  236. package/python/vendor/openpyxl/utils/bound_dictionary.py +26 -0
  237. package/python/vendor/openpyxl/utils/cell.py +240 -0
  238. package/python/vendor/openpyxl/utils/dataframe.py +87 -0
  239. package/python/vendor/openpyxl/utils/datetime.py +140 -0
  240. package/python/vendor/openpyxl/utils/escape.py +43 -0
  241. package/python/vendor/openpyxl/utils/exceptions.py +34 -0
  242. package/python/vendor/openpyxl/utils/formulas.py +24 -0
  243. package/python/vendor/openpyxl/utils/indexed_list.py +49 -0
  244. package/python/vendor/openpyxl/utils/inference.py +60 -0
  245. package/python/vendor/openpyxl/utils/protection.py +22 -0
  246. package/python/vendor/openpyxl/utils/units.py +108 -0
  247. package/python/vendor/openpyxl/workbook/__init__.py +4 -0
  248. package/python/vendor/openpyxl/workbook/_writer.py +197 -0
  249. package/python/vendor/openpyxl/workbook/child.py +166 -0
  250. package/python/vendor/openpyxl/workbook/defined_name.py +189 -0
  251. package/python/vendor/openpyxl/workbook/external_link/__init__.py +3 -0
  252. package/python/vendor/openpyxl/workbook/external_link/external.py +190 -0
  253. package/python/vendor/openpyxl/workbook/external_reference.py +18 -0
  254. package/python/vendor/openpyxl/workbook/function_group.py +36 -0
  255. package/python/vendor/openpyxl/workbook/properties.py +151 -0
  256. package/python/vendor/openpyxl/workbook/protection.py +163 -0
  257. package/python/vendor/openpyxl/workbook/smart_tags.py +56 -0
  258. package/python/vendor/openpyxl/workbook/views.py +155 -0
  259. package/python/vendor/openpyxl/workbook/web.py +98 -0
  260. package/python/vendor/openpyxl/workbook/workbook.py +438 -0
  261. package/python/vendor/openpyxl/worksheet/__init__.py +1 -0
  262. package/python/vendor/openpyxl/worksheet/_read_only.py +190 -0
  263. package/python/vendor/openpyxl/worksheet/_reader.py +472 -0
  264. package/python/vendor/openpyxl/worksheet/_write_only.py +160 -0
  265. package/python/vendor/openpyxl/worksheet/_writer.py +390 -0
  266. package/python/vendor/openpyxl/worksheet/cell_range.py +512 -0
  267. package/python/vendor/openpyxl/worksheet/cell_watch.py +34 -0
  268. package/python/vendor/openpyxl/worksheet/controls.py +107 -0
  269. package/python/vendor/openpyxl/worksheet/copier.py +70 -0
  270. package/python/vendor/openpyxl/worksheet/custom.py +35 -0
  271. package/python/vendor/openpyxl/worksheet/datavalidation.py +202 -0
  272. package/python/vendor/openpyxl/worksheet/dimensions.py +306 -0
  273. package/python/vendor/openpyxl/worksheet/drawing.py +14 -0
  274. package/python/vendor/openpyxl/worksheet/errors.py +93 -0
  275. package/python/vendor/openpyxl/worksheet/filters.py +486 -0
  276. package/python/vendor/openpyxl/worksheet/formula.py +51 -0
  277. package/python/vendor/openpyxl/worksheet/header_footer.py +270 -0
  278. package/python/vendor/openpyxl/worksheet/hyperlink.py +46 -0
  279. package/python/vendor/openpyxl/worksheet/merge.py +141 -0
  280. package/python/vendor/openpyxl/worksheet/ole.py +133 -0
  281. package/python/vendor/openpyxl/worksheet/page.py +174 -0
  282. package/python/vendor/openpyxl/worksheet/pagebreak.py +94 -0
  283. package/python/vendor/openpyxl/worksheet/picture.py +8 -0
  284. package/python/vendor/openpyxl/worksheet/print_settings.py +184 -0
  285. package/python/vendor/openpyxl/worksheet/properties.py +97 -0
  286. package/python/vendor/openpyxl/worksheet/protection.py +120 -0
  287. package/python/vendor/openpyxl/worksheet/related.py +17 -0
  288. package/python/vendor/openpyxl/worksheet/scenario.py +105 -0
  289. package/python/vendor/openpyxl/worksheet/smart_tag.py +78 -0
  290. package/python/vendor/openpyxl/worksheet/table.py +385 -0
  291. package/python/vendor/openpyxl/worksheet/views.py +155 -0
  292. package/python/vendor/openpyxl/worksheet/worksheet.py +907 -0
  293. package/python/vendor/openpyxl/writer/__init__.py +1 -0
  294. package/python/vendor/openpyxl/writer/excel.py +295 -0
  295. package/python/vendor/openpyxl/writer/theme.py +291 -0
  296. package/python/vendor/openpyxl/xml/__init__.py +42 -0
  297. package/python/vendor/openpyxl/xml/constants.py +129 -0
  298. package/python/vendor/openpyxl/xml/functions.py +87 -0
  299. package/watchlist/package.json +1 -1
@@ -0,0 +1,240 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+ """
4
+ Collection of utilities used within the package and also available for client code
5
+ """
6
+ from functools import lru_cache
7
+ from itertools import chain, product
8
+ from string import ascii_uppercase, digits
9
+ import re
10
+
11
+ from .exceptions import CellCoordinatesException
12
+
13
+ # constants
14
+ COORD_RE = re.compile(r'^[$]?([A-Za-z]{1,3})[$]?(\d+)$')
15
+ COL_RANGE = """[A-Z]{1,3}:[A-Z]{1,3}:"""
16
+ ROW_RANGE = r"""\d+:\d+:"""
17
+ RANGE_EXPR = r"""
18
+ [$]?(?P<min_col>[A-Za-z]{1,3})?
19
+ [$]?(?P<min_row>\d+)?
20
+ (:[$]?(?P<max_col>[A-Za-z]{1,3})?
21
+ [$]?(?P<max_row>\d+)?)?
22
+ """
23
+ ABSOLUTE_RE = re.compile('^' + RANGE_EXPR +'$', re.VERBOSE)
24
+ SHEET_TITLE = r"""
25
+ (('(?P<quoted>([^']|'')*)')|(?P<notquoted>[^'^ ^!]*))!"""
26
+ SHEETRANGE_RE = re.compile("""{0}(?P<cells>{1})(?=,?)""".format(
27
+ SHEET_TITLE, RANGE_EXPR), re.VERBOSE)
28
+
29
+
30
+ def get_column_interval(start, end):
31
+ """
32
+ Given the start and end columns, return all the columns in the series.
33
+
34
+ The start and end columns can be either column letters or 1-based
35
+ indexes.
36
+ """
37
+ if isinstance(start, str):
38
+ start = column_index_from_string(start)
39
+ if isinstance(end, str):
40
+ end = column_index_from_string(end)
41
+ return [get_column_letter(x) for x in range(start, end + 1)]
42
+
43
+
44
+ def coordinate_from_string(coord_string):
45
+ """Convert a coordinate string like 'B12' to a tuple ('B', 12)"""
46
+ match = COORD_RE.match(coord_string)
47
+ if not match:
48
+ msg = f"Invalid cell coordinates ({coord_string})"
49
+ raise CellCoordinatesException(msg)
50
+ column, row = match.groups()
51
+ row = int(row)
52
+ if not row:
53
+ msg = f"There is no row 0 ({coord_string})"
54
+ raise CellCoordinatesException(msg)
55
+ return column, row
56
+
57
+
58
+ def absolute_coordinate(coord_string):
59
+ """Convert a coordinate to an absolute coordinate string (B12 -> $B$12)"""
60
+ m = ABSOLUTE_RE.match(coord_string)
61
+ if not m:
62
+ raise ValueError(f"{coord_string} is not a valid coordinate range")
63
+
64
+ d = m.groupdict('')
65
+ for k, v in d.items():
66
+ if v:
67
+ d[k] = f"${v}"
68
+
69
+ if d['max_col'] or d['max_row']:
70
+ fmt = "{min_col}{min_row}:{max_col}{max_row}"
71
+ else:
72
+ fmt = "{min_col}{min_row}"
73
+ return fmt.format(**d)
74
+
75
+
76
+ __decimal_to_alpha = [""] + list(ascii_uppercase)
77
+
78
+ @lru_cache(maxsize=None)
79
+ def get_column_letter(col_idx):
80
+ """
81
+ Convert decimal column position to its ASCII (base 26) form.
82
+
83
+ Because column indices are 1-based, strides are actually pow(26, n) + 26
84
+ Hence, a correction is applied between pow(26, n) and pow(26, 2) + 26 to
85
+ prevent and additional column letter being prepended
86
+
87
+ "A" == 1 == pow(26, 0)
88
+ "Z" == 26 == pow(26, 0) + 26 // decimal equivalent 10
89
+ "AA" == 27 == pow(26, 1) + 1
90
+ "ZZ" == 702 == pow(26, 2) + 26 // decimal equivalent 100
91
+ """
92
+
93
+ if not 1 <= col_idx <= 18278:
94
+ raise ValueError("Invalid column index {0}".format(col_idx))
95
+
96
+ result = []
97
+
98
+ if col_idx < 26:
99
+ return __decimal_to_alpha[col_idx]
100
+
101
+ while col_idx:
102
+ col_idx, remainder = divmod(col_idx, 26)
103
+ result.insert(0, __decimal_to_alpha[remainder])
104
+ if not remainder:
105
+ col_idx -= 1
106
+ result.insert(0, "Z")
107
+
108
+ return "".join(result)
109
+
110
+
111
+ __alpha_to_decimal = {letter:pos for pos, letter in enumerate(ascii_uppercase, 1)}
112
+ __powers = (1, 26, 676)
113
+
114
+ @lru_cache(maxsize=None)
115
+ def column_index_from_string(col):
116
+ """
117
+ Convert ASCII column name (base 26) to decimal with 1-based index
118
+
119
+ Characters represent descending multiples of powers of 26
120
+
121
+ "AFZ" == 26 * pow(26, 0) + 6 * pow(26, 1) + 1 * pow(26, 2)
122
+ """
123
+ error_msg = f"'{col}' is not a valid column name. Column names are from A to ZZZ"
124
+ if len(col) > 3:
125
+ raise ValueError(error_msg)
126
+ idx = 0
127
+ col = reversed(col.upper())
128
+ for letter, power in zip(col, __powers):
129
+ try:
130
+ pos = __alpha_to_decimal[letter]
131
+ except KeyError:
132
+ raise ValueError(error_msg)
133
+ idx += pos * power
134
+ if not 0 < idx < 18279:
135
+ raise ValueError(error_msg)
136
+ return idx
137
+
138
+
139
+ def range_boundaries(range_string):
140
+ """
141
+ Convert a range string into a tuple of boundaries:
142
+ (min_col, min_row, max_col, max_row)
143
+ Cell coordinates will be converted into a range with the cell at both end
144
+ """
145
+ msg = "{0} is not a valid coordinate or range".format(range_string)
146
+ m = ABSOLUTE_RE.match(range_string)
147
+ if not m:
148
+ raise ValueError(msg)
149
+
150
+ min_col, min_row, sep, max_col, max_row = m.groups()
151
+
152
+ if sep:
153
+ cols = min_col, max_col
154
+ rows = min_row, max_row
155
+
156
+ if not (
157
+ all(cols + rows) or
158
+ all(cols) and not any(rows) or
159
+ all(rows) and not any(cols)
160
+ ):
161
+ raise ValueError(msg)
162
+
163
+ if min_col is not None:
164
+ min_col = column_index_from_string(min_col)
165
+
166
+ if min_row is not None:
167
+ min_row = int(min_row)
168
+
169
+ if max_col is not None:
170
+ max_col = column_index_from_string(max_col)
171
+ else:
172
+ max_col = min_col
173
+
174
+ if max_row is not None:
175
+ max_row = int(max_row)
176
+ else:
177
+ max_row = min_row
178
+
179
+ return min_col, min_row, max_col, max_row
180
+
181
+
182
+ def rows_from_range(range_string):
183
+ """
184
+ Get individual addresses for every cell in a range.
185
+ Yields one row at a time.
186
+ """
187
+ min_col, min_row, max_col, max_row = range_boundaries(range_string)
188
+ rows = range(min_row, max_row + 1)
189
+ cols = [get_column_letter(col) for col in range(min_col, max_col + 1)]
190
+ for row in rows:
191
+ yield tuple('{0}{1}'.format(col, row) for col in cols)
192
+
193
+
194
+ def cols_from_range(range_string):
195
+ """
196
+ Get individual addresses for every cell in a range.
197
+ Yields one row at a time.
198
+ """
199
+ min_col, min_row, max_col, max_row = range_boundaries(range_string)
200
+ rows = range(min_row, max_row+1)
201
+ cols = (get_column_letter(col) for col in range(min_col, max_col+1))
202
+ for col in cols:
203
+ yield tuple('{0}{1}'.format(col, row) for row in rows)
204
+
205
+
206
+ def coordinate_to_tuple(coordinate):
207
+ """
208
+ Convert an Excel style coordinate to (row, column) tuple
209
+ """
210
+ for idx, c in enumerate(coordinate):
211
+ if c in digits:
212
+ break
213
+ col = coordinate[:idx]
214
+ row = coordinate[idx:]
215
+ return int(row), column_index_from_string(col)
216
+
217
+
218
+ def range_to_tuple(range_string):
219
+ """
220
+ Convert a worksheet range to the sheetname and maximum and minimum
221
+ coordinate indices
222
+ """
223
+ m = SHEETRANGE_RE.match(range_string)
224
+ if m is None:
225
+ raise ValueError("Value must be of the form sheetname!A1:E4")
226
+ sheetname = m.group("quoted") or m.group("notquoted")
227
+ cells = m.group("cells")
228
+ boundaries = range_boundaries(cells)
229
+ return sheetname, boundaries
230
+
231
+
232
+ def quote_sheetname(sheetname):
233
+ """
234
+ Add quotes around sheetnames if they contain spaces.
235
+ """
236
+ if "'" in sheetname:
237
+ sheetname = sheetname.replace("'", "''")
238
+
239
+ sheetname = u"'{0}'".format(sheetname)
240
+ return sheetname
@@ -0,0 +1,87 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+ from itertools import accumulate
4
+ import operator
5
+ import numpy
6
+ from openpyxl.compat.product import prod
7
+
8
+
9
+ def dataframe_to_rows(df, index=True, header=True):
10
+ """
11
+ Convert a Pandas dataframe into something suitable for passing into a worksheet.
12
+ If index is True then the index will be included, starting one row below the header.
13
+ If header is True then column headers will be included starting one column to the right.
14
+ Formatting should be done by client code.
15
+ """
16
+ from pandas import Timestamp
17
+
18
+ if header:
19
+ if df.columns.nlevels > 1:
20
+ rows = expand_index(df.columns, header)
21
+ else:
22
+ rows = [list(df.columns.values)]
23
+ for row in rows:
24
+ n = []
25
+ for v in row:
26
+ if isinstance(v, numpy.datetime64):
27
+ v = Timestamp(v)
28
+ n.append(v)
29
+ row = n
30
+ if index:
31
+ row = [None]*df.index.nlevels + row
32
+ yield row
33
+
34
+ if index:
35
+ yield df.index.names
36
+
37
+ expanded = ([v] for v in df.index)
38
+ if df.index.nlevels > 1:
39
+ expanded = expand_index(df.index)
40
+
41
+ # Using the expanded index is preferable to df.itertuples(index=True) so that we have 'None' inserted where applicable
42
+ for (df_index, row) in zip(expanded, df.itertuples(index=False)):
43
+ row = list(row)
44
+ if index:
45
+ row = df_index + row
46
+ yield row
47
+
48
+
49
+ def expand_index(index, header=False):
50
+ """
51
+ Expand axis or column Multiindex
52
+ For columns use header = True
53
+ For axes use header = False (default)
54
+ """
55
+
56
+ # For each element of the index, zip the members with the previous row
57
+ # If the 2 elements of the zipped list do not match, we can insert the new value into the row
58
+ # or if an earlier member was different, all later members should be added to the row
59
+ values = list(index.values)
60
+ previous_value = [None] * len(values[0])
61
+ result = []
62
+
63
+ for value in values:
64
+ row = [None] * len(value)
65
+
66
+ # Once there's a difference in member of an index with the prior index, we need to store all subsequent members in the row
67
+ prior_change = False
68
+ for idx, (current_index_member, previous_index_member) in enumerate(zip(value, previous_value)):
69
+
70
+ if current_index_member != previous_index_member or prior_change:
71
+ row[idx] = current_index_member
72
+ prior_change = True
73
+
74
+ previous_value = value
75
+
76
+ # If this is for a row index, we're already returning a row so just yield
77
+ if not header:
78
+ yield row
79
+ else:
80
+ result.append(row)
81
+
82
+ # If it's for a header, we need to transpose to get it in row order
83
+ # Example: result = [['A', 'A'], [None, 'B']] -> [['A', None], ['A', 'B']]
84
+ if header:
85
+ result = numpy.array(result).transpose().tolist()
86
+ for row in result:
87
+ yield row
@@ -0,0 +1,140 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+ """Manage Excel date weirdness."""
4
+
5
+ # Python stdlib imports
6
+ import datetime
7
+ from math import isnan
8
+ import re
9
+
10
+
11
+ # constants
12
+ MAC_EPOCH = datetime.datetime(1904, 1, 1)
13
+ WINDOWS_EPOCH = datetime.datetime(1899, 12, 30)
14
+ CALENDAR_WINDOWS_1900 = 2415018.5 # Julian date of WINDOWS_EPOCH
15
+ CALENDAR_MAC_1904 = 2416480.5 # Julian date of MAC_EPOCH
16
+ CALENDAR_WINDOWS_1900 = WINDOWS_EPOCH
17
+ CALENDAR_MAC_1904 = MAC_EPOCH
18
+ SECS_PER_DAY = 86400
19
+
20
+ ISO_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
21
+ ISO_REGEX = re.compile(r'''
22
+ (?P<date>(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}))?T?
23
+ (?P<time>(?P<hour>\d{2}):(?P<minute>\d{2})(:(?P<second>\d{2})(?P<microsecond>\.\d{1,3})?)?)?Z?''',
24
+ re.VERBOSE)
25
+ ISO_DURATION = re.compile(r'PT((?P<hours>\d+)H)?((?P<minutes>\d+)M)?((?P<seconds>\d+(\.\d{1,3})?)S)?')
26
+
27
+
28
+ def to_ISO8601(dt):
29
+ """Convert from a datetime to a timestamp string."""
30
+ if hasattr(dt, "microsecond") and dt.microsecond:
31
+ return dt.isoformat(timespec="milliseconds")
32
+ return dt.isoformat()
33
+
34
+
35
+ def from_ISO8601(formatted_string):
36
+ """Convert from a timestamp string to a datetime object. According to
37
+ 18.17.4 in the specification the following ISO 8601 formats are
38
+ supported.
39
+
40
+ Dates B.1.1 and B.2.1
41
+ Times B.1.2 and B.2.2
42
+ Datetimes B.1.3 and B.2.3
43
+
44
+ There is no concept of timedeltas in the specification, but Excel
45
+ writes them (in strict OOXML mode), so these are also understood.
46
+ """
47
+ if not formatted_string:
48
+ return None
49
+
50
+ match = ISO_REGEX.match(formatted_string)
51
+ if match and any(match.groups()):
52
+ parts = match.groupdict(0)
53
+ for key in ["year", "month", "day", "hour", "minute", "second"]:
54
+ if parts[key]:
55
+ parts[key] = int(parts[key])
56
+
57
+ if parts["microsecond"]:
58
+ parts["microsecond"] = int(float(parts['microsecond']) * 1_000_000)
59
+
60
+ if not parts["date"]:
61
+ dt = datetime.time(parts['hour'], parts['minute'], parts['second'], parts["microsecond"])
62
+ elif not parts["time"]:
63
+ dt = datetime.date(parts['year'], parts['month'], parts['day'])
64
+ else:
65
+ del parts["time"]
66
+ del parts["date"]
67
+ dt = datetime.datetime(**parts)
68
+ return dt
69
+
70
+ match = ISO_DURATION.match(formatted_string)
71
+ if match and any(match.groups()):
72
+ parts = match.groupdict(0)
73
+ for key, val in parts.items():
74
+ if val:
75
+ parts[key] = float(val)
76
+ return datetime.timedelta(**parts)
77
+
78
+ raise ValueError("Invalid datetime value {}".format(formatted_string))
79
+
80
+
81
+ def to_excel(dt, epoch=WINDOWS_EPOCH):
82
+ """Convert Python datetime to Excel serial"""
83
+ if isinstance(dt, datetime.time):
84
+ return time_to_days(dt)
85
+ if isinstance(dt, datetime.timedelta):
86
+ return timedelta_to_days(dt)
87
+ if isnan(dt.year): # Pandas supports Not a Date
88
+ return
89
+
90
+ if not hasattr(dt, "date"):
91
+ dt = datetime.datetime.combine(dt, datetime.time())
92
+
93
+ # rebase on epoch and adjust for < 1900-03-01
94
+ days = (dt - epoch).days
95
+ if 0 < days <= 60 and epoch == WINDOWS_EPOCH:
96
+ days -= 1
97
+ return days + time_to_days(dt)
98
+
99
+
100
+ def from_excel(value, epoch=WINDOWS_EPOCH, timedelta=False):
101
+ """Convert Excel serial to Python datetime"""
102
+ if value is None:
103
+ return
104
+
105
+ if timedelta:
106
+ td = datetime.timedelta(days=value)
107
+ if td.microseconds:
108
+ # round to millisecond precision
109
+ td = datetime.timedelta(seconds=td.total_seconds() // 1,
110
+ microseconds=round(td.microseconds, -3))
111
+ return td
112
+
113
+ day, fraction = divmod(value, 1)
114
+ diff = datetime.timedelta(milliseconds=round(fraction * SECS_PER_DAY * 1000))
115
+ if 0 <= value < 1 and diff.days == 0:
116
+ return days_to_time(diff)
117
+ if 0 < value < 60 and epoch == WINDOWS_EPOCH:
118
+ day += 1
119
+ return epoch + datetime.timedelta(days=day) + diff
120
+
121
+
122
+ def time_to_days(value):
123
+ """Convert a time value to fractions of day"""
124
+ return (
125
+ (value.hour * 3600)
126
+ + (value.minute * 60)
127
+ + value.second
128
+ + value.microsecond / 10**6
129
+ ) / SECS_PER_DAY
130
+
131
+
132
+ def timedelta_to_days(value):
133
+ """Convert a timedelta value to fractions of a day"""
134
+ return value.total_seconds() / SECS_PER_DAY
135
+
136
+
137
+ def days_to_time(value):
138
+ mins, seconds = divmod(value.seconds, 60)
139
+ hours, mins = divmod(mins, 60)
140
+ return datetime.time(hours, mins, seconds, value.microseconds)
@@ -0,0 +1,43 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+ """
4
+ OOXML has non-standard escaping for characters < \031
5
+ """
6
+
7
+ import re
8
+
9
+
10
+ def escape(value):
11
+ r"""
12
+ Convert ASCII < 31 to OOXML: \n == _x + hex(ord(\n)) + _
13
+ """
14
+
15
+ CHAR_REGEX = re.compile(r"[\001-\031]")
16
+
17
+ def _sub(match):
18
+ """
19
+ Callback to escape chars
20
+ """
21
+ return "_x{:0>4x}_".format(ord(match.group(0)))
22
+
23
+ return CHAR_REGEX.sub(_sub, value)
24
+
25
+
26
+ def unescape(value):
27
+ r"""
28
+ Convert escaped strings to ASCIII: _x000a_ == \n
29
+ """
30
+
31
+
32
+ ESCAPED_REGEX = re.compile("_x([0-9A-Fa-f]{4})_")
33
+
34
+ def _sub(match):
35
+ """
36
+ Callback to unescape chars
37
+ """
38
+ return chr(int(match.group(1), 16))
39
+
40
+ if "_x" in value:
41
+ value = ESCAPED_REGEX.sub(_sub, value)
42
+
43
+ return value
@@ -0,0 +1,34 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+
4
+ """Definitions for openpyxl shared exception classes."""
5
+
6
+
7
+ class CellCoordinatesException(Exception):
8
+ """Error for converting between numeric and A1-style cell references."""
9
+
10
+
11
+ class IllegalCharacterError(Exception):
12
+ """The data submitted which cannot be used directly in Excel files. It
13
+ must be removed or escaped."""
14
+
15
+
16
+ class NamedRangeException(Exception):
17
+ """Error for badly formatted named ranges."""
18
+
19
+
20
+ class SheetTitleException(Exception):
21
+ """Error for bad sheet names."""
22
+
23
+
24
+ class InvalidFileException(Exception):
25
+ """Error for trying to open a non-ooxml file."""
26
+
27
+
28
+ class ReadOnlyWorkbookException(Exception):
29
+ """Error for trying to modify a read-only workbook"""
30
+
31
+
32
+ class WorkbookAlreadySaved(Exception):
33
+ """Error when attempting to perform operations on a dump workbook
34
+ while it has already been dumped once"""
@@ -0,0 +1,24 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+ """
4
+ List of builtin formulae
5
+ """
6
+
7
+ FORMULAE = ("CUBEKPIMEMBER", "CUBEMEMBER", "CUBEMEMBERPROPERTY", "CUBERANKEDMEMBER", "CUBESET", "CUBESETCOUNT", "CUBEVALUE", "DAVERAGE", "DCOUNT", "DCOUNTA", "DGET", "DMAX", "DMIN", "DPRODUCT", "DSTDEV", "DSTDEVP", "DSUM", "DVAR", "DVARP", "DATE", "DATEDIF", "DATEVALUE", "DAY", "DAYS360", "EDATE", "EOMONTH", "HOUR", "MINUTE", "MONTH", "NETWORKDAYS", "NETWORKDAYS.INTL", "NOW", "SECOND", "TIME", "TIMEVALUE", "TODAY", "WEEKDAY", "WEEKNUM", "WORKDAY", "WORKDAY.INTL", "YEAR", "YEARFRAC", "BESSELI", "BESSELJ", "BESSELK", "BESSELY", "BIN2DEC", "BIN2HEX", "BIN2OCT", "COMPLEX", "CONVERT", "DEC2BIN", "DEC2HEX", "DEC2OCT", "DELTA", "ERF", "ERFC", "GESTEP", "HEX2BIN", "HEX2DEC", "HEX2OCT", "IMABS", "IMAGINARY", "IMARGUMENT", "IMCONJUGATE", "IMCOS", "IMDIV", "IMEXP", "IMLN", "IMLOG10", "IMLOG2", "IMPOWER", "IMPRODUCT", "IMREAL", "IMSIN", "IMSQRT", "IMSUB", "IMSUM", "OCT2BIN", "OCT2DEC", "OCT2HEX", "ACCRINT", "ACCRINTM", "AMORDEGRC", "AMORLINC", "COUPDAYBS", "COUPDAYS", "COUPDAYSNC", "COUPNCD", "COUPNUM", "COUPPCD", "CUMIPMT", "CUMPRINC", "DB", "DDB", "DISC", "DOLLARDE", "DOLLARFR", "DURATION", "EFFECT", "FV", "FVSCHEDULE", "INTRATE", "IPMT", "IRR", "ISPMT", "MDURATION", "MIRR", "NOMINAL", "NPER", "NPV", "ODDFPRICE", "ODDFYIELD", "ODDLPRICE", "ODDLYIELD", "PMT", "PPMT", "PRICE", "PRICEDISC", "PRICEMAT", "PV", "RATE", "RECEIVED", "SLN", "SYD", "TBILLEQ", "TBILLPRICE", "TBILLYIELD", "VDB", "XIRR", "XNPV", "YIELD", "YIELDDISC", "YIELDMAT", "CELL", "ERROR.TYPE", "INFO", "ISBLANK", "ISERR", "ISERROR", "ISEVEN", "ISLOGICAL", "ISNA", "ISNONTEXT", "ISNUMBER", "ISODD", "ISREF", "ISTEXT", "N", "NA", "TYPE", "AND", "FALSE", "IF", "IFERROR", "NOT", "OR", "TRUE", "ADDRESS", "AREAS", "CHOOSE", "COLUMN", "COLUMNS", "GETPIVOTDATA", "HLOOKUP", "HYPERLINK", "INDEX", "INDIRECT", "LOOKUP", "MATCH", "OFFSET", "ROW", "ROWS", "RTD", "TRANSPOSE", "VLOOKUP", "ABS", "ACOS", "ACOSH", "ASIN", "ASINH", "ATAN", "ATAN2", "ATANH", "CEILING", "COMBIN", "COS", "COSH", "DEGREES", "ECMA.CEILING", "EVEN", "EXP", "FACT", "FACTDOUBLE", "FLOOR", "GCD", "INT", "ISO.CEILING", "LCM", "LN", "LOG", "LOG10", "MDETERM", "MINVERSE", "MMULT", "MOD", "MROUND", "MULTINOMIAL", "ODD", "PI", "POWER", "PRODUCT", "QUOTIENT", "RADIANS", "RAND", "RANDBETWEEN", "ROMAN", "ROUND", "ROUNDDOWN", "ROUNDUP", "SERIESSUM", "SIGN", "SIN", "SINH", "SQRT", "SQRTPI", "SUBTOTAL", "SUM", "SUMIF", "SUMIFS", "SUMPRODUCT", "SUMSQ", "SUMX2MY2", "SUMX2PY2", "SUMXMY2", "TAN", "TANH", "TRUNC", "AVEDEV", "AVERAGE", "AVERAGEA", "AVERAGEIF", "AVERAGEIFS", "BETADIST", "BETAINV", "BINOMDIST", "CHIDIST", "CHIINV", "CHITEST", "CONFIDENCE", "CORREL", "COUNT", "COUNTA", "COUNTBLANK", "COUNTIF", "COUNTIFS", "COVAR", "CRITBINOM", "DEVSQ", "EXPONDIST", "FDIST", "FINV", "FISHER", "FISHERINV", "FORECAST", "FREQUENCY", "FTEST", "GAMMADIST", "GAMMAINV", "GAMMALN", "GEOMEAN", "GROWTH", "HARMEAN", "HYPGEOMDIST", "INTERCEPT", "KURT", "LARGE", "LINEST", "LOGEST", "LOGINV", "LOGNORMDIST", "MAX", "MAXA", "MEDIAN", "MIN", "MINA", "MODE", "NEGBINOMDIST", "NORMDIST", "NORMINV", "NORMSDIST", "NORMSINV", "PEARSON", "PERCENTILE", "PERCENTRANK", "PERMUT", "POISSON", "PROB", "QUARTILE", "RANK", "RSQ", "SKEW", "SLOPE", "SMALL", "STANDARDIZE", "STDEV", "STDEVA", "STDEVP", "STDEVPA", "STEYX", "TDIST", "TINV", "TREND", "TRIMMEAN", "TTEST", "VAR", "VARA", "VARP", "VARPA", "WEIBULL", "ZTEST", "ASC", "BAHTTEXT", "CHAR", "CLEAN", "CODE", "CONCATENATE", "DOLLAR", "EXACT", "FIND", "FINDB", "FIXED", "JIS", "LEFT", "LEFTB", "LEN", "LENB", "LOWER", "MID", "MIDB", "PHONETIC", "PROPER", "REPLACE", "REPLACEB", "REPT", "RIGHT", "RIGHTB", "SEARCH", "SEARCHB", "SUBSTITUTE", "T", "TEXT", "TRIM", "UPPER", "VALUE")
8
+
9
+ FORMULAE = frozenset(FORMULAE)
10
+
11
+
12
+ from openpyxl.formula import Tokenizer
13
+
14
+
15
+ def validate(formula):
16
+ """
17
+ Utility function for checking whether a formula is syntactically correct
18
+ """
19
+ assert formula.startswith("=")
20
+ formula = Tokenizer(formula)
21
+ for t in formula.items:
22
+ if t.type == "FUNC" and t.subtype == "OPEN":
23
+ if not t.value.startswith("_xlfn.") and t.value[:-1] not in FORMULAE:
24
+ raise ValueError(f"Unknown function {t.value} in {formula.formula}. The function may need a prefix")
@@ -0,0 +1,49 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+
4
+ class IndexedList(list):
5
+ """
6
+ List with optimised access by value
7
+ Based on Alex Martelli's recipe
8
+
9
+ http://code.activestate.com/recipes/52303-the-auxiliary-dictionary-idiom-for-sequences-with-/
10
+ """
11
+
12
+ _dict = {}
13
+
14
+ def __init__(self, iterable=None):
15
+ self.clean = True
16
+ self._dict = {}
17
+ if iterable is not None:
18
+ self.clean = False
19
+ for idx, val in enumerate(iterable):
20
+ self._dict[val] = idx
21
+ list.append(self, val)
22
+
23
+ def _rebuild_dict(self):
24
+ self._dict = {}
25
+ idx = 0
26
+ for value in self:
27
+ if value not in self._dict:
28
+ self._dict[value] = idx
29
+ idx += 1
30
+ self.clean = True
31
+
32
+ def __contains__(self, value):
33
+ if not self.clean:
34
+ self._rebuild_dict()
35
+ return value in self._dict
36
+
37
+ def index(self, value):
38
+ if value in self:
39
+ return self._dict[value]
40
+ raise ValueError
41
+
42
+ def append(self, value):
43
+ if value not in self._dict:
44
+ self._dict[value] = len(self)
45
+ list.append(self, value)
46
+
47
+ def add(self, value):
48
+ self.append(value)
49
+ return self._dict[value]
@@ -0,0 +1,60 @@
1
+ # Copyright (c) 2010-2024 openpyxl
2
+
3
+ """
4
+ Type inference functions
5
+ """
6
+ import datetime
7
+ import re
8
+
9
+ from openpyxl.styles import numbers
10
+
11
+ PERCENT_REGEX = re.compile(r'^(?P<number>\-?[0-9]*\.?[0-9]*\s?)\%$')
12
+ TIME_REGEX = re.compile(r"""
13
+ ^(?: # HH:MM and HH:MM:SS
14
+ (?P<hour>[0-1]{0,1}[0-9]{2}):
15
+ (?P<minute>[0-5][0-9]):?
16
+ (?P<second>[0-5][0-9])?$)
17
+ |
18
+ ^(?: # MM:SS.
19
+ ([0-5][0-9]):
20
+ ([0-5][0-9])?\.
21
+ (?P<microsecond>\d{1,6}))
22
+ """, re.VERBOSE)
23
+ NUMBER_REGEX = re.compile(r'^-?([\d]|[\d]+\.[\d]*|\.[\d]+|[1-9][\d]+\.?[\d]*)((E|e)[-+]?[\d]+)?$')
24
+
25
+
26
+ def cast_numeric(value):
27
+ """Explicitly convert a string to a numeric value"""
28
+ if NUMBER_REGEX.match(value):
29
+ try:
30
+ return int(value)
31
+ except ValueError:
32
+ return float(value)
33
+
34
+
35
+ def cast_percentage(value):
36
+ """Explicitly convert a string to numeric value and format as a
37
+ percentage"""
38
+ match = PERCENT_REGEX.match(value)
39
+ if match:
40
+ return float(match.group('number')) / 100
41
+
42
+
43
+
44
+ def cast_time(value):
45
+ """Explicitly convert a string to a number and format as datetime or
46
+ time"""
47
+ match = TIME_REGEX.match(value)
48
+ if match:
49
+ if match.group("microsecond") is not None:
50
+ value = value[:12]
51
+ pattern = "%M:%S.%f"
52
+ #fmt = numbers.FORMAT_DATE_TIME5
53
+ elif match.group('second') is None:
54
+ #fmt = numbers.FORMAT_DATE_TIME3
55
+ pattern = "%H:%M"
56
+ else:
57
+ pattern = "%H:%M:%S"
58
+ #fmt = numbers.FORMAT_DATE_TIME6
59
+ value = datetime.datetime.strptime(value, pattern)
60
+ return value.time()