"""JXLS批注工具类"""
from typing import List
from openpyxl.worksheet.worksheet import Worksheet
from .excel_helper import ExcelHelper
class JxlsHelper:
"""JXLS批注生成和管理工具类"""
def __init__(self):
self.excel_helper = ExcelHelper()
def create_area_annotation(self, last_cell: str) -> str:
"""创建jx:area批注"""
return f'jx:area(lastCell="{last_cell}")'
def create_each_annotation(self, items: str, var: str, last_cell: str) -> str:
"""创建jx:each批注"""
return f'jx:each(items="{items}" var="{var}" lastCell="{last_cell}")'
def calculate_last_cell(self, column_count: int, row: int) -> str:
"""计算lastCell坐标"""
column_letter = self.excel_helper.calculate_column_letter(column_count)
return f"{column_letter}{row}"
def add_annotations_to_cell(
self,
worksheet: Worksheet,
row: int,
column: int,
annotations: List[str]
) -> None:
"""向单元格添加多个批注"""
if not annotations:
return
# 将所有批注合并为一个注释
comment_text = "\n".join(annotations)
self.excel_helper.add_comment_to_cell(worksheet, row, column, comment_text)
def generate_jxls_annotations(
self,
collect_name: str,
item_variable: str,
column_count: int,
data_row: int = 2
) -> tuple[str, str]:
"""生成完整的JXLS批注"""
last_cell = self.calculate_last_cell(column_count, data_row)
area_annotation = self.create_area_annotation(last_cell)
each_annotation = self.create_each_annotation(collect_name, item_variable, last_cell)
return area_annotation, each_annotation
def apply_jxls_annotations(
self,
worksheet: Worksheet,
collect_name: str,
item_variable: str,
column_count: int,
header_row: int = 1,
data_row: int = 2
) -> tuple[str, str]:
"""应用JXLS批注到工作表"""
# 生成批注
area_annotation, each_annotation = self.generate_jxls_annotations(
collect_name, item_variable, column_count, data_row
)
# A1单元格添加area批注
# self.add_annotations_to_cell(
# worksheet, header_row, 1, [area_annotation]
# )
# A2单元格添加each批注
self.add_annotations_to_cell(
worksheet, data_row, 1, [area_annotation, each_annotation]
)
return area_annotation, each_annotation