utils.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import re
  2. from typing import Dict
  3. def excel_column_name_to_number(s):
  4. n = 0
  5. for c in s.upper():
  6. n = n * 26 + ord(c) - 64
  7. return n
  8. def excel_column_number_to_name(n):
  9. s = ""
  10. while n:
  11. n, r = divmod(n - 1, 26)
  12. s = chr(r + 65) + s
  13. return s
  14. def calculate_excel_range_bottom_right_cell(start_cell, data):
  15. col, row = re.match(r"([A-Za-z]+)(\d+)", start_cell).groups()
  16. rows = len(data)
  17. cols = len(data[0]) if rows else 0
  18. end_col = excel_column_name_to_number(col) + cols - 1
  19. end_row = int(row) + rows - 1
  20. return f"{excel_column_number_to_name(end_col)}{end_row}"
  21. def value_with_mapped_note(value: str, map_dict: Dict[str, str]) -> str:
  22. if not map_dict:
  23. return value
  24. if value not in map_dict:
  25. return value
  26. return f"{value}({map_dict[value]})"
  27. def convert_storage_unit(value, from_unit, to_unit):
  28. """
  29. 存储单位换算核心函数
  30. :param value: 要转换的数值(数字类型)
  31. :param from_unit: 原始单位(如 B/KB/MB/GB/TB,不区分大小写)
  32. :param to_unit: 目标单位(如 B/KB/MB/GB/TB,不区分大小写)
  33. :return: 换算后的结果(保留2位小数)
  34. """
  35. # 定义单位与字节(B)的换算比例(1单位 = 多少B)
  36. unit_map = {
  37. 'b': 1,
  38. 'kb': 1024,
  39. 'mb': 1024 ** 2,
  40. 'gb': 1024 ** 3,
  41. 'tb': 1024 ** 4
  42. }
  43. # 统一单位为小写,避免大小写问题
  44. from_unit = from_unit.strip().lower()
  45. to_unit = to_unit.strip().lower()
  46. # 校验单位是否合法
  47. if from_unit not in unit_map or to_unit not in unit_map:
  48. raise ValueError(f"不支持的单位!仅支持:{list(unit_map.keys())}")
  49. # 校验数值是否合法
  50. try:
  51. value = float(value)
  52. except ValueError:
  53. raise ValueError("数值必须是数字(如 1024、2.5 等)")
  54. # 换算逻辑:先转为字节,再转为目标单位
  55. bytes_value = value * unit_map[from_unit] # 原始值转字节
  56. result = bytes_value / unit_map[to_unit] # 字节转目标单位
  57. return round(result, 2) # 保留2位小数,提升可读性