feat: replace with control

This commit is contained in:
zzs 2025-03-26 11:09:42 +08:00
parent 8e896cf683
commit 9852d06e15

View File

@ -85,7 +85,7 @@ def QueryAll():
doc = XSCRIPTCONTEXT.getDocument()
bookmarks = doc.getBookmarks()
bookmark_names = bookmarks.getElementNames()
filtered_bookmarks = [bk_name for bk_name in bookmark_names if '_' not in bk_name and ':' not in bk_name]
filtered_bookmarks = [bk_name for bk_name in bookmark_names if not bk_name.startswith('_') and ':' not in bk_name]
result = {"text": [], "table": []}
# tables = doc.getTextTables()
@ -235,6 +235,74 @@ def InsertRow(location_bookmark_name, data, start_row_index=-1):
except Exception as e:
raise RuntimeError(f"插入行时发生错误: {str(e)}")
def BatchInsertRowWithContentControl(data_array):
"""
批量插入行
"""
doc = XSCRIPTCONTEXT.getDocument()
tables = doc.getTextTables()
bookmarks = doc.getBookmarks()
bookmark_in_table_position = QueryBookmarkPositionInTable(tables, bookmarks)
for arr_obj in data_array:
location_bookmark_name = arr_obj.get('location_bookmark_name')
data = arr_obj.get('data')
start_row_index = arr_obj.get('start_row_index', -1) # 默认值为 -1
if location_bookmark_name not in bookmark_in_table_position:
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
handle_table_index = bookmark_in_table_position[location_bookmark_name]["tableIndex"]
try:
handle_table = tables.getByIndex(handle_table_index)
except IndexError:
raise IndexError(f"表格索引 {handle_table_index} 超出范围")
col_count = handle_table.getColumns().getCount()
row_count = handle_table.getRows().getCount()
if not data or len(data) == 0:
return
if any(len(row) != col_count for row in data):
raise ValueError(f"数据列数不匹配,表格有 {col_count}")
try:
row_count = handle_table.getRows().getCount()
rows_to_insert = len(data)
if rows_to_insert > 0:
# 确定插入位置
if start_row_index != -1 and 0 <= start_row_index < row_count:
insert_pos = start_row_index + 1 # 在指定行下方插入
else:
insert_pos = row_count # 插入到表格末尾
# 批量插入所有新行
handle_table.getRows().insertByIndex(insert_pos, rows_to_insert)
# 填充数据到新插入的行
for data_row_idx, row_data in enumerate(data):
target_row = insert_pos + data_row_idx # 计算目标行索引
for col_idx, cell_value in enumerate(row_data):
cell = handle_table.getCellByPosition(col_idx, target_row)
# cell.setString(str(cell_value))
# 创建文本控件并赋值 -----------------------------
cell_text = cell.getText()
cell_text.setString("") # 清空原有内容
text_control = doc.createInstance("com.sun.star.text.TextField.Input")
text_control.setPropertyValue("Content", str(cell_value))
cursor = cell_text.createTextCursor()
cell_text.insertTextContent(cursor, text_control, False)
except Exception as e:
raise RuntimeError(f"插入行时发生错误: {str(e)}")
def BatchInsertRow(data_array):
"""
批量插入行
@ -521,9 +589,10 @@ def ReplaceTextAndInsertTableRow(json_str):
Replace(data["text"])
BatchInsertRow(data["table"])
model = XSCRIPTCONTEXT.getDocument()
controller = model.getCurrentController()
controller.refresh()
def ReplaceTextAndInsertTableRowWithContentControl(json_str):
data = json.loads(json_str)
ReplaceBookmarksWithControls(data["text"])
BatchInsertRowWithContentControl(data["table"])
def returnWithJSON(data):
return json.dumps(data, ensure_ascii=False)
@ -541,18 +610,21 @@ def SaveDocument():
xstorable.store()
return True
except Exception as e:
print("保存失败:", e)
print("err:", e)
return False
def DebugCallReplaceBookmarksWithControls():
ReplaceBookmarksWithControls({"合同编号_A": "11111", "合同名称_A": "22222"})
def replace_bookmarks_with_controls():
def ReplaceBookmarksWithControls(bookmark_name_value_map={}):
doc = XSCRIPTCONTEXT.getDocument()
bookmarks = doc.getBookmarks()
controller = doc.getCurrentController()
for name in reversed([bm.getName() for bm in bookmarks]):
try:
if name.startswith('_'):
continue
bookmark = bookmarks.getByName(name)
anchor = bookmark.getAnchor()
@ -562,8 +634,10 @@ def replace_bookmarks_with_controls():
# 创建文本控件并设置内容
text_control = doc.createInstance("com.sun.star.text.TextField.Input")
text_control.setPropertyValue("Content", original_text)
# text_control.setPropertyValue("BookmarkName", name) # 正确属性名
if (bookmark_name_value_map.get(name)):
text_control.setPropertyValue("Content", bookmark_name_value_map.get(name))
else
text_control.setPropertyValue("Content", original_text)
# 替换原书签内容为控件
cursor.setString("")
@ -575,7 +649,53 @@ def replace_bookmarks_with_controls():
doc.getBookmarks().addNew(name, new_cursor)
except Exception as e:
print(f"错误:{str(e)}")
print(f"error{str(e)}")
def NextEditableZone(current_index):
"""
根据索引定位可编辑区域支持循环
Args:
current_index (int/str): 0 开始的索引支持字符串或整数类型
"""
# 强制转换为整数 -----------------------------
try:
current_index = int(current_index)
except (ValueError, TypeError):
print(f"err {current_index} cant convert to int")
return
doc = XSCRIPTCONTEXT.getDocument()
controller = doc.getCurrentController()
view_cursor = controller.getViewCursor()
# 收集所有可编辑控件的锚点
text_fields = doc.getTextFields().createEnumeration()
editable_anchors = []
while text_fields.hasMoreElements():
field = text_fields.nextElement()
if field.supportsService("com.sun.star.text.TextField.Input"):
try:
anchor = field.getAnchor()
editable_anchors.append(anchor)
except Exception:
continue
# 无控件时直接返回
if not editable_anchors:
print("文档中无可编辑控件")
return
# 计算有效索引(循环逻辑)
total = len(editable_anchors)
effective_index = current_index % total # 此处不再报错
# 定位到目标控件
target_anchor = editable_anchors[effective_index]
view_cursor.gotoRange(target_anchor, False)
controller.select(target_anchor) # 选中控件(可选)
g_exportedScripts = (
@ -597,6 +717,9 @@ g_exportedScripts = (
DebugCallInsertBookmark,
DebugCallUpdateBookmark,
DebugCallDeleteBookmark,
replace_bookmarks_with_controls,
SaveDocument
ReplaceBookmarksWithControls,
ReplaceTextAndInsertTableRowWithContentControl,
DebugCallReplaceBookmarksWithControls,
SaveDocument,
NextEditableZone
)