Compare commits
2 Commits
9852d06e15
...
b835ed6cb3
Author | SHA1 | Date | |
---|---|---|---|
![]() |
b835ed6cb3 | ||
![]() |
ca9bb2771c |
417
BookmarkOP.py
417
BookmarkOP.py
@ -1,5 +1,21 @@
|
|||||||
import json
|
import json
|
||||||
import time
|
|
||||||
|
|
||||||
|
def Replace(bookmark_name_value_map):
|
||||||
|
"""
|
||||||
|
替换所有书签
|
||||||
|
Args:
|
||||||
|
bookmark_name_value_map: 书签名称和新值的映射
|
||||||
|
"""
|
||||||
|
|
||||||
|
doc = XSCRIPTCONTEXT.getDocument()
|
||||||
|
bookmarks = doc.getBookmarks()
|
||||||
|
for bookmark_name, new_value in bookmark_name_value_map.items():
|
||||||
|
if bookmarks.hasByName(bookmark_name):
|
||||||
|
bookmark = bookmarks.getByName(bookmark_name)
|
||||||
|
anchor = bookmark.getAnchor()
|
||||||
|
anchor.setString(new_value)
|
||||||
|
|
||||||
|
|
||||||
def ReplaceOne(bookmark_obj_collection, bookmark_name, new_value):
|
def ReplaceOne(bookmark_obj_collection, bookmark_name, new_value):
|
||||||
"""
|
"""
|
||||||
@ -16,30 +32,6 @@ def ReplaceOne(bookmark_obj_collection, bookmark_name, new_value):
|
|||||||
anchor.setString(new_value)
|
anchor.setString(new_value)
|
||||||
|
|
||||||
|
|
||||||
def ReplaceAll(bookmark_obj_collection, bookmark_name_value_map):
|
|
||||||
"""
|
|
||||||
替换所有书签
|
|
||||||
Args:
|
|
||||||
bookmark_obj_collection: 书签对象集合
|
|
||||||
bookmark_name_value_map: 书签名称和新值的映射
|
|
||||||
"""
|
|
||||||
|
|
||||||
for bookmark_name, new_value in bookmark_name_value_map.items():
|
|
||||||
ReplaceOne(bookmark_obj_collection, bookmark_name, new_value)
|
|
||||||
|
|
||||||
|
|
||||||
def Replace(bookmark_name_value_map):
|
|
||||||
"""
|
|
||||||
替换所有书签
|
|
||||||
Args:
|
|
||||||
bookmark_name_value_map: 书签名称和新值的映射
|
|
||||||
"""
|
|
||||||
|
|
||||||
doc = XSCRIPTCONTEXT.getDocument()
|
|
||||||
bookmarks = doc.getBookmarks()
|
|
||||||
ReplaceAll(bookmarks, bookmark_name_value_map)
|
|
||||||
|
|
||||||
|
|
||||||
def ReplaceWithJSON(json_str):
|
def ReplaceWithJSON(json_str):
|
||||||
"""
|
"""
|
||||||
替换所有书签
|
替换所有书签
|
||||||
@ -51,21 +43,6 @@ def ReplaceWithJSON(json_str):
|
|||||||
Replace(bookmark_name_value_map)
|
Replace(bookmark_name_value_map)
|
||||||
|
|
||||||
|
|
||||||
def DebugCallReplace():
|
|
||||||
"""
|
|
||||||
调试调用
|
|
||||||
"""
|
|
||||||
|
|
||||||
Replace({"bb1": "P1", "bb2": "P2", "bb3": "P3", "bb4": "P4"})
|
|
||||||
|
|
||||||
|
|
||||||
def DebugCallReplaceList():
|
|
||||||
"""
|
|
||||||
调试调用,替换list
|
|
||||||
"""
|
|
||||||
|
|
||||||
Replace({"list": "1\r2\r3\r4"})
|
|
||||||
|
|
||||||
def QueryAll():
|
def QueryAll():
|
||||||
"""
|
"""
|
||||||
查询所有书签,表格中的书签获取对应表格index
|
查询所有书签,表格中的书签获取对应表格index
|
||||||
@ -85,27 +62,14 @@ def QueryAll():
|
|||||||
doc = XSCRIPTCONTEXT.getDocument()
|
doc = XSCRIPTCONTEXT.getDocument()
|
||||||
bookmarks = doc.getBookmarks()
|
bookmarks = doc.getBookmarks()
|
||||||
bookmark_names = bookmarks.getElementNames()
|
bookmark_names = bookmarks.getElementNames()
|
||||||
filtered_bookmarks = [bk_name for bk_name in bookmark_names if not bk_name.startswith('_') 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": []}
|
result = {"text": [], "table": []}
|
||||||
|
|
||||||
# tables = doc.getTextTables()
|
|
||||||
# bookmark_in_table_position = QueryBookmarkPositionInTable(tables, bookmarks)
|
|
||||||
|
|
||||||
existing_table_indices = {}
|
|
||||||
|
|
||||||
for bk_name in filtered_bookmarks:
|
for bk_name in filtered_bookmarks:
|
||||||
# if bk_name in bookmark_in_table_position:
|
|
||||||
# table_index = bookmark_in_table_position[bk_name]["tableIndex"]
|
|
||||||
# if table_index in existing_table_indices:
|
|
||||||
# index = existing_table_indices[table_index]
|
|
||||||
# result["table"][index]["bookmark"].append(bk_name)
|
|
||||||
# else:
|
|
||||||
# new_entry = {"tableIndex": table_index, "bookmark": [bk_name]}
|
|
||||||
# result["table"].append(new_entry)
|
|
||||||
# existing_table_indices[table_index] = (
|
|
||||||
# len(result["table"]) - 1
|
|
||||||
# ) # 更新索引记录
|
|
||||||
# else:
|
|
||||||
result["text"].append(bk_name)
|
result["text"].append(bk_name)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
@ -116,59 +80,59 @@ def QueryAllWithJSON():
|
|||||||
|
|
||||||
def QueryBookmarkPositionInTable(tables, bookmarks):
|
def QueryBookmarkPositionInTable(tables, bookmarks):
|
||||||
"""
|
"""
|
||||||
查询书签在表格中的位置
|
查询书签在表格中的位置。
|
||||||
{'bk1': {'tableIndex': 0, 'row': 0, 'col': 0}, 'bk2': {'tableIndex': 0, 'row': 0, 'col': 2}}
|
|
||||||
|
参数:
|
||||||
|
tables: 表格集合 (XIndexAccess)
|
||||||
|
bookmarks: 书签集合 (XIndexAccess)
|
||||||
|
|
||||||
|
返回:
|
||||||
|
一个字典,格式为 {'书签名': {'tableIndex': 表格索引, 'row': 行号}}
|
||||||
"""
|
"""
|
||||||
|
result = {}
|
||||||
|
|
||||||
bookmark_names = bookmarks.getElementNames()
|
# 遍历所有书签
|
||||||
|
for b in range(bookmarks.getCount()):
|
||||||
|
bookmark = bookmarks.getByIndex(b)
|
||||||
|
bookmark_name = bookmark.getName()
|
||||||
|
x_range = bookmark.getAnchor() # 获取书签的锚点
|
||||||
|
x_text = x_range.getText() # 获取书签所在的文本对象
|
||||||
|
|
||||||
bookmark_position = {}
|
# 遍历所有表格
|
||||||
|
for t in range(tables.getCount()):
|
||||||
|
table = tables.getByIndex(t)
|
||||||
|
|
||||||
for table_index in range(tables.getCount()):
|
# 遍历表格中的每一行
|
||||||
table = tables.getByIndex(table_index)
|
rows = table.getRows().getCount()
|
||||||
|
for i in range(rows):
|
||||||
|
# 动态确定当前行的最大列数
|
||||||
|
max_cols = 0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
cell = table.getCellByPosition(max_cols, i)
|
||||||
|
max_cols += 1
|
||||||
|
except Exception:
|
||||||
|
break
|
||||||
|
|
||||||
col_count = table.getColumns().getCount()
|
for j in range(max_cols):
|
||||||
row_count = table.getRows().getCount()
|
cell = table.getCellByPosition(j, i)
|
||||||
|
cell_text = cell.getText()
|
||||||
|
|
||||||
for row in range(row_count):
|
if cell_text == x_text:
|
||||||
for col in range(col_count):
|
result[bookmark_name] = {
|
||||||
cell = table.getCellByPosition(col, row)
|
'tableIndex': t,
|
||||||
cell_text_obj = cell.getText()
|
'row': i,
|
||||||
|
'col': j
|
||||||
for bk_name in bookmark_names:
|
|
||||||
bookmark_obj = bookmarks.getByName(bk_name)
|
|
||||||
bookmark_text_obj = bookmark_obj.getAnchor().getText()
|
|
||||||
if cell_text_obj == bookmark_text_obj:
|
|
||||||
bookmark_position[bk_name] = {
|
|
||||||
"tableIndex": table_index,
|
|
||||||
"col": col,
|
|
||||||
"row": row,
|
|
||||||
}
|
}
|
||||||
|
break
|
||||||
return bookmark_position
|
else:
|
||||||
|
continue
|
||||||
|
break
|
||||||
def CreateRow(table, row_count):
|
else:
|
||||||
"""
|
continue
|
||||||
创建表格行
|
|
||||||
"""
|
|
||||||
table.getRows().insertByIndex(table.getRows().getCount(), row_count)
|
|
||||||
|
|
||||||
|
|
||||||
def FindTableIndex(table_bookmarks, location_bookmark_name):
|
|
||||||
"""
|
|
||||||
找到表格索引
|
|
||||||
"""
|
|
||||||
handle_table_index = -1
|
|
||||||
for table_info in table_bookmarks:
|
|
||||||
if location_bookmark_name in table_info["bookmark"]:
|
|
||||||
handle_table_index = table_info["tableIndex"]
|
|
||||||
break
|
break
|
||||||
|
|
||||||
if handle_table_index == -1:
|
return result
|
||||||
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
|
||||||
return handle_table_index
|
|
||||||
|
|
||||||
|
|
||||||
def InsertRowWithJSON(json_str):
|
def InsertRowWithJSON(json_str):
|
||||||
"""
|
"""
|
||||||
@ -194,7 +158,9 @@ def InsertRow(location_bookmark_name, data, start_row_index=-1):
|
|||||||
if location_bookmark_name not in bookmark_in_table_position:
|
if location_bookmark_name not in bookmark_in_table_position:
|
||||||
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
||||||
|
|
||||||
handle_table_index = bookmark_in_table_position[location_bookmark_name]["tableIndex"]
|
handle_table_index = bookmark_in_table_position[location_bookmark_name][
|
||||||
|
"tableIndex"
|
||||||
|
]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
handle_table = tables.getByIndex(handle_table_index)
|
handle_table = tables.getByIndex(handle_table_index)
|
||||||
@ -207,9 +173,6 @@ def InsertRow(location_bookmark_name, data, start_row_index=-1):
|
|||||||
if not data or len(data) == 0:
|
if not data or len(data) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
if any(len(row) != col_count for row in data):
|
|
||||||
raise ValueError(f"数据列数不匹配,表格有 {col_count} 列")
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
row_count = handle_table.getRows().getCount()
|
row_count = handle_table.getRows().getCount()
|
||||||
rows_to_insert = len(data)
|
rows_to_insert = len(data)
|
||||||
@ -231,9 +194,8 @@ def InsertRow(location_bookmark_name, data, start_row_index=-1):
|
|||||||
cell = handle_table.getCellByPosition(col_idx, target_row)
|
cell = handle_table.getCellByPosition(col_idx, target_row)
|
||||||
cell.setString(str(cell_value))
|
cell.setString(str(cell_value))
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(f"插入行时发生错误: {str(e)}")
|
raise RuntimeError(f"err: {str(e)}")
|
||||||
|
|
||||||
def BatchInsertRowWithContentControl(data_array):
|
def BatchInsertRowWithContentControl(data_array):
|
||||||
"""
|
"""
|
||||||
@ -245,13 +207,15 @@ def BatchInsertRowWithContentControl(data_array):
|
|||||||
bookmark_in_table_position = QueryBookmarkPositionInTable(tables, bookmarks)
|
bookmark_in_table_position = QueryBookmarkPositionInTable(tables, bookmarks)
|
||||||
|
|
||||||
for arr_obj in data_array:
|
for arr_obj in data_array:
|
||||||
location_bookmark_name = arr_obj.get('location_bookmark_name')
|
location_bookmark_name = arr_obj.get("location_bookmark_name")
|
||||||
data = arr_obj.get('data')
|
data = arr_obj.get("data")
|
||||||
start_row_index = arr_obj.get('start_row_index', -1) # 默认值为 -1
|
start_row_index = arr_obj.get("start_row_index", -1) # 默认值为 -1
|
||||||
if location_bookmark_name not in bookmark_in_table_position:
|
if location_bookmark_name not in bookmark_in_table_position:
|
||||||
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
||||||
|
|
||||||
handle_table_index = bookmark_in_table_position[location_bookmark_name]["tableIndex"]
|
handle_table_index = bookmark_in_table_position[location_bookmark_name][
|
||||||
|
"tableIndex"
|
||||||
|
]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
handle_table = tables.getByIndex(handle_table_index)
|
handle_table = tables.getByIndex(handle_table_index)
|
||||||
@ -264,8 +228,8 @@ def BatchInsertRowWithContentControl(data_array):
|
|||||||
if not data or len(data) == 0:
|
if not data or len(data) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
if any(len(row) != col_count for row in data):
|
# if any(len(row) != col_count for row in data):
|
||||||
raise ValueError(f"数据列数不匹配,表格有 {col_count} 列")
|
# raise ValueError(f"数据列数不匹配,表格有 {col_count} 列")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
row_count = handle_table.getRows().getCount()
|
row_count = handle_table.getRows().getCount()
|
||||||
@ -286,23 +250,29 @@ def BatchInsertRowWithContentControl(data_array):
|
|||||||
target_row = insert_pos + data_row_idx # 计算目标行索引
|
target_row = insert_pos + data_row_idx # 计算目标行索引
|
||||||
for col_idx, cell_value in enumerate(row_data):
|
for col_idx, cell_value in enumerate(row_data):
|
||||||
cell = handle_table.getCellByPosition(col_idx, target_row)
|
cell = handle_table.getCellByPosition(col_idx, target_row)
|
||||||
# cell.setString(str(cell_value))
|
|
||||||
# 创建文本控件并赋值 -----------------------------
|
|
||||||
cell_text = cell.getText()
|
cell_text = cell.getText()
|
||||||
cell_text.setString("") # 清空原有内容
|
|
||||||
|
|
||||||
text_control = doc.createInstance("com.sun.star.text.TextField.Input")
|
# === 清空单元格 ===
|
||||||
text_control.setPropertyValue("Content", str(cell_value))
|
cell_text.setString("")
|
||||||
|
|
||||||
|
# === 创建内容控件 ===
|
||||||
|
content_control = doc.createInstance(
|
||||||
|
"com.sun.star.text.ContentControl"
|
||||||
|
)
|
||||||
|
|
||||||
|
# === 插入控件到单元格 ===
|
||||||
cursor = cell_text.createTextCursor()
|
cursor = cell_text.createTextCursor()
|
||||||
cell_text.insertTextContent(cursor, text_control, False)
|
cell_text.insertTextContent(cursor, content_control, False)
|
||||||
|
|
||||||
|
# === 设置控件内容 ===
|
||||||
|
cc_text = content_control.getText()
|
||||||
|
cc_cursor = cc_text.createTextCursor()
|
||||||
|
cc_cursor.setString(str(cell_value))
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(f"插入行时发生错误: {str(e)}")
|
raise RuntimeError(f"插入行时发生错误: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def BatchInsertRow(data_array):
|
def BatchInsertRow(data_array):
|
||||||
"""
|
"""
|
||||||
批量插入行
|
批量插入行
|
||||||
@ -314,13 +284,15 @@ def BatchInsertRow(data_array):
|
|||||||
bookmark_in_table_position = QueryBookmarkPositionInTable(tables, bookmarks)
|
bookmark_in_table_position = QueryBookmarkPositionInTable(tables, bookmarks)
|
||||||
|
|
||||||
for arr_obj in data_array:
|
for arr_obj in data_array:
|
||||||
location_bookmark_name = arr_obj.get('location_bookmark_name')
|
location_bookmark_name = arr_obj.get("location_bookmark_name")
|
||||||
data = arr_obj.get('data')
|
data = arr_obj.get("data")
|
||||||
start_row_index = arr_obj.get('start_row_index', -1) # 默认值为 -1
|
start_row_index = arr_obj.get("start_row_index", -1) # 默认值为 -1
|
||||||
if location_bookmark_name not in bookmark_in_table_position:
|
if location_bookmark_name not in bookmark_in_table_position:
|
||||||
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
||||||
|
|
||||||
handle_table_index = bookmark_in_table_position[location_bookmark_name]["tableIndex"]
|
handle_table_index = bookmark_in_table_position[location_bookmark_name][
|
||||||
|
"tableIndex"
|
||||||
|
]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
handle_table = tables.getByIndex(handle_table_index)
|
handle_table = tables.getByIndex(handle_table_index)
|
||||||
@ -357,32 +329,21 @@ def BatchInsertRow(data_array):
|
|||||||
cell = handle_table.getCellByPosition(col_idx, target_row)
|
cell = handle_table.getCellByPosition(col_idx, target_row)
|
||||||
cell.setString(str(cell_value))
|
cell.setString(str(cell_value))
|
||||||
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(f"插入行时发生错误: {str(e)}")
|
raise RuntimeError(f"插入行时发生错误: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def InsertRowWithJSONDefineCol(json_str):
|
|
||||||
"""
|
|
||||||
插入行
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def DebugCallInsertRow():
|
|
||||||
"""
|
|
||||||
调试调用
|
|
||||||
"""
|
|
||||||
InsertRow("t1", [["1", "2"], ["4", "5"]], 0)
|
|
||||||
|
|
||||||
|
|
||||||
def DeleteRowWithJSON(json_str):
|
def DeleteRowWithJSON(json_str):
|
||||||
"""
|
"""
|
||||||
删除行
|
删除行
|
||||||
"""
|
"""
|
||||||
data = json.loads(json_str)
|
data = json.loads(json_str)
|
||||||
DeleteRow(data["location_bookmark_name"], data["start_row_index"], data["delete_row_count"])
|
DeleteRow(
|
||||||
|
data["location_bookmark_name"],
|
||||||
|
data["start_row_index"],
|
||||||
|
data["delete_row_count"],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def DeleteRow(location_bookmark_name, start_row_index, delete_row_count=-1):
|
def DeleteRow(location_bookmark_name, start_row_index, delete_row_count=-1):
|
||||||
"""
|
"""
|
||||||
@ -393,10 +354,6 @@ def DeleteRow(location_bookmark_name, start_row_index, delete_row_count=-1):
|
|||||||
start_row_index: 起始行位置(删除行包含本行)
|
start_row_index: 起始行位置(删除行包含本行)
|
||||||
delete_row_count: 删除的行数
|
delete_row_count: 删除的行数
|
||||||
"""
|
"""
|
||||||
# bookmark_info = QueryAll()
|
|
||||||
# table_bookmarks = bookmark_info["table"]
|
|
||||||
# handle_table_index = FindTableIndex(table_bookmarks, location_bookmark_name)
|
|
||||||
|
|
||||||
doc = XSCRIPTCONTEXT.getDocument()
|
doc = XSCRIPTCONTEXT.getDocument()
|
||||||
tables = doc.getTextTables()
|
tables = doc.getTextTables()
|
||||||
bookmarks = doc.getBookmarks()
|
bookmarks = doc.getBookmarks()
|
||||||
@ -404,8 +361,9 @@ def DeleteRow(location_bookmark_name, start_row_index, delete_row_count=-1):
|
|||||||
if location_bookmark_name not in bookmark_in_table_position:
|
if location_bookmark_name not in bookmark_in_table_position:
|
||||||
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
raise ValueError(f"未找到书签 {location_bookmark_name} 对应的表格")
|
||||||
|
|
||||||
handle_table_index = bookmark_in_table_position[location_bookmark_name]["tableIndex"]
|
handle_table_index = bookmark_in_table_position[location_bookmark_name][
|
||||||
|
"tableIndex"
|
||||||
|
]
|
||||||
|
|
||||||
handle_table = tables.getByIndex(handle_table_index)
|
handle_table = tables.getByIndex(handle_table_index)
|
||||||
row_count = handle_table.getRows().getCount()
|
row_count = handle_table.getRows().getCount()
|
||||||
@ -419,14 +377,7 @@ def DeleteRow(location_bookmark_name, start_row_index, delete_row_count=-1):
|
|||||||
try:
|
try:
|
||||||
handle_table.getRows().removeByIndex(start_row_index, delete_row_count)
|
handle_table.getRows().removeByIndex(start_row_index, delete_row_count)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(f"删除行时发生错误: {str(e)}")
|
raise RuntimeError(f"err: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
def DebugCallDeleteRow():
|
|
||||||
"""
|
|
||||||
调试调用
|
|
||||||
"""
|
|
||||||
DeleteRow("h1", 1, 2)
|
|
||||||
|
|
||||||
|
|
||||||
def LocateBookmark(bookmark_name):
|
def LocateBookmark(bookmark_name):
|
||||||
@ -438,7 +389,7 @@ def LocateBookmark(bookmark_name):
|
|||||||
doc = XSCRIPTCONTEXT.getDocument()
|
doc = XSCRIPTCONTEXT.getDocument()
|
||||||
|
|
||||||
if False == doc.getBookmarks().hasByName(bookmark_name):
|
if False == doc.getBookmarks().hasByName(bookmark_name):
|
||||||
return
|
return
|
||||||
|
|
||||||
bookmark = doc.getBookmarks().getByName(bookmark_name)
|
bookmark = doc.getBookmarks().getByName(bookmark_name)
|
||||||
|
|
||||||
@ -467,11 +418,6 @@ def LocateBookmark(bookmark_name):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(f"定位书签失败: {str(e)}") from e
|
raise RuntimeError(f"定位书签失败: {str(e)}") from e
|
||||||
|
|
||||||
def DebugCallLocateBookmarkLo1():
|
|
||||||
LocateBookmark("lo1")
|
|
||||||
|
|
||||||
def DebugCallLocateBookmarkLo2():
|
|
||||||
LocateBookmark("lo2")
|
|
||||||
|
|
||||||
def InsertBookmark(bookmark_name):
|
def InsertBookmark(bookmark_name):
|
||||||
"""
|
"""
|
||||||
@ -513,14 +459,6 @@ def InsertBookmark(bookmark_name):
|
|||||||
raise RuntimeError(f"插入书签失败: {str(e)}") from e
|
raise RuntimeError(f"插入书签失败: {str(e)}") from e
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def DebugCallInsertBookmark():
|
|
||||||
"""
|
|
||||||
调试调用
|
|
||||||
"""
|
|
||||||
InsertBookmark("bookmark_" + str(time.time()))
|
|
||||||
|
|
||||||
|
|
||||||
def UpdateBookmark(bookmark_name, new_value):
|
def UpdateBookmark(bookmark_name, new_value):
|
||||||
"""
|
"""
|
||||||
修改书签名称(通过删除旧书签 + 插入新书签实现)
|
修改书签名称(通过删除旧书签 + 插入新书签实现)
|
||||||
@ -541,11 +479,6 @@ def UpdateBookmark(bookmark_name, new_value):
|
|||||||
old_bookmark = bookmarks.getByName(bookmark_name)
|
old_bookmark = bookmarks.getByName(bookmark_name)
|
||||||
old_bookmark.setName(new_value)
|
old_bookmark.setName(new_value)
|
||||||
|
|
||||||
def DebugCallUpdateBookmark():
|
|
||||||
"""
|
|
||||||
调试调用
|
|
||||||
"""
|
|
||||||
UpdateBookmark("ole_bookmark", "new_bookmark")
|
|
||||||
|
|
||||||
def DeleteBookmark(bookmark_name):
|
def DeleteBookmark(bookmark_name):
|
||||||
"""
|
"""
|
||||||
@ -566,12 +499,6 @@ def DeleteBookmark(bookmark_name):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def DebugCallDeleteBookmark():
|
|
||||||
"""
|
|
||||||
调试调用
|
|
||||||
"""
|
|
||||||
DeleteBookmark("remove_me")
|
|
||||||
|
|
||||||
|
|
||||||
def CreateTable(location_bookmark_name, data):
|
def CreateTable(location_bookmark_name, data):
|
||||||
"""
|
"""
|
||||||
@ -581,6 +508,7 @@ def CreateTable(location_bookmark_name, data):
|
|||||||
data: 二维数组,用于填充表格数据
|
data: 二维数组,用于填充表格数据
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def ReplaceTextAndInsertTableRow(json_str):
|
def ReplaceTextAndInsertTableRow(json_str):
|
||||||
"""
|
"""
|
||||||
替换文本和表格
|
替换文本和表格
|
||||||
@ -589,14 +517,17 @@ def ReplaceTextAndInsertTableRow(json_str):
|
|||||||
Replace(data["text"])
|
Replace(data["text"])
|
||||||
BatchInsertRow(data["table"])
|
BatchInsertRow(data["table"])
|
||||||
|
|
||||||
|
|
||||||
def ReplaceTextAndInsertTableRowWithContentControl(json_str):
|
def ReplaceTextAndInsertTableRowWithContentControl(json_str):
|
||||||
data = json.loads(json_str)
|
data = json.loads(json_str)
|
||||||
|
# BatchInsertRowWithContentControl(data["table"])
|
||||||
ReplaceBookmarksWithControls(data["text"])
|
ReplaceBookmarksWithControls(data["text"])
|
||||||
BatchInsertRowWithContentControl(data["table"])
|
|
||||||
|
|
||||||
def returnWithJSON(data):
|
def returnWithJSON(data):
|
||||||
return json.dumps(data, ensure_ascii=False)
|
return json.dumps(data, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
def SaveDocument():
|
def SaveDocument():
|
||||||
# 获取当前文档对象
|
# 获取当前文档对象
|
||||||
model = XSCRIPTCONTEXT.getDocument()
|
model = XSCRIPTCONTEXT.getDocument()
|
||||||
@ -604,6 +535,7 @@ def SaveDocument():
|
|||||||
try:
|
try:
|
||||||
# 检查文档是否支持保存(XStorable 接口)
|
# 检查文档是否支持保存(XStorable 接口)
|
||||||
from com.sun.star.frame import XStorable
|
from com.sun.star.frame import XStorable
|
||||||
|
|
||||||
xstorable = model.uno_getAdapter(XStorable)
|
xstorable = model.uno_getAdapter(XStorable)
|
||||||
|
|
||||||
# 调用保存方法(覆盖原文件)
|
# 调用保存方法(覆盖原文件)
|
||||||
@ -613,47 +545,59 @@ def SaveDocument():
|
|||||||
print("err:", e)
|
print("err:", e)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def DebugCallReplaceBookmarksWithControls():
|
|
||||||
ReplaceBookmarksWithControls({"合同编号_A": "11111", "合同名称_A": "22222"})
|
|
||||||
|
|
||||||
|
|
||||||
def ReplaceBookmarksWithControls(bookmark_name_value_map={}):
|
def ReplaceBookmarksWithControls(bookmark_name_value_map={}):
|
||||||
|
# 获取文档对象
|
||||||
doc = XSCRIPTCONTEXT.getDocument()
|
doc = XSCRIPTCONTEXT.getDocument()
|
||||||
bookmarks = doc.getBookmarks()
|
bookmarks = doc.getBookmarks()
|
||||||
|
|
||||||
for name in reversed([bm.getName() for bm in bookmarks]):
|
# 过滤包含下划线前缀的书签
|
||||||
|
bookmark_names = [name for name in bookmarks.getElementNames() if not name.startswith("_")]
|
||||||
|
|
||||||
|
# 遍历所有需要处理的书签
|
||||||
|
for name in bookmark_names:
|
||||||
try:
|
try:
|
||||||
if name.startswith('_'):
|
# 检查书签是否存在
|
||||||
|
if not bookmarks.hasByName(name):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# 获取书签对象及其锚点
|
||||||
bookmark = bookmarks.getByName(name)
|
bookmark = bookmarks.getByName(name)
|
||||||
anchor = bookmark.getAnchor()
|
anchor = bookmark.getAnchor()
|
||||||
|
|
||||||
# 获取书签内容
|
# 获取书签的原始内容
|
||||||
cursor = anchor.getText().createTextCursorByRange(anchor)
|
original_text = anchor.getString()
|
||||||
original_text = cursor.getString()
|
replace_value = bookmark_name_value_map.get(name, original_text)
|
||||||
|
|
||||||
# 创建文本控件并设置内容
|
# === 第1步:创建内容控件 ===
|
||||||
text_control = doc.createInstance("com.sun.star.text.TextField.Input")
|
content_control = doc.createInstance("com.sun.star.text.ContentControl")
|
||||||
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("")
|
text = anchor.getText()
|
||||||
anchor.getText().insertTextContent(cursor, text_control, False)
|
anchor.setString("")
|
||||||
|
|
||||||
# 重新插入原书签到控件后
|
# 插入内容控件
|
||||||
new_cursor = cursor.getText().createTextCursorByRange(cursor)
|
text.insertTextContent(anchor, content_control, True)
|
||||||
new_cursor.goRight(1, False)
|
|
||||||
doc.getBookmarks().addNew(name, new_cursor)
|
# 设置控件内容
|
||||||
|
cc_cursor = content_control.getText().createTextCursor()
|
||||||
|
cc_cursor.setString(replace_value)
|
||||||
|
|
||||||
|
# === 第2步:清理旧书签 ===
|
||||||
|
bookmark.dispose()
|
||||||
|
|
||||||
|
# === 第3步:创建新书签 ===
|
||||||
|
cc_anchor = content_control.getText().getAnchor()
|
||||||
|
new_bookmark = doc.createInstance("com.sun.star.text.Bookmark")
|
||||||
|
new_bookmark.setName(name)
|
||||||
|
new_bookmark.attach(cc_anchor)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"error{str(e)}")
|
print(f"处理书签 '{name}' 时出错: {e}")
|
||||||
|
|
||||||
def NextEditableZone(current_index):
|
def NextEditableZone(current_index):
|
||||||
"""
|
"""
|
||||||
根据索引定位可编辑区域(支持循环)
|
根据索引定位名称包含'permission'的书签(支持循环)
|
||||||
Args:
|
Args:
|
||||||
current_index (int/str): 从 0 开始的索引,支持字符串或整数类型
|
current_index (int/str): 从 0 开始的索引,支持字符串或整数类型
|
||||||
"""
|
"""
|
||||||
@ -661,41 +605,56 @@ def NextEditableZone(current_index):
|
|||||||
try:
|
try:
|
||||||
current_index = int(current_index)
|
current_index = int(current_index)
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
print(f"err {current_index} cant convert to int")
|
print(f"错误:无法将 {current_index} 转换为整数")
|
||||||
return
|
return
|
||||||
|
|
||||||
doc = XSCRIPTCONTEXT.getDocument()
|
doc = XSCRIPTCONTEXT.getDocument()
|
||||||
controller = doc.getCurrentController()
|
controller = doc.getCurrentController()
|
||||||
view_cursor = controller.getViewCursor()
|
view_cursor = controller.getViewCursor()
|
||||||
|
|
||||||
# 收集所有可编辑控件的锚点
|
bookmarks = doc.getBookmarks()
|
||||||
text_fields = doc.getTextFields().createEnumeration()
|
bookmark_names = bookmarks.getElementNames()
|
||||||
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
|
|
||||||
|
|
||||||
# 无控件时直接返回
|
# 过滤包含permission的书签(不区分大小写)
|
||||||
|
permission_bookmarks = [name for name in bookmark_names if not name.startswith("_")]
|
||||||
|
|
||||||
|
editable_anchors = []
|
||||||
|
for bm_name in permission_bookmarks:
|
||||||
|
try:
|
||||||
|
bookmark = bookmarks.getByName(bm_name)
|
||||||
|
anchor = bookmark.getAnchor()
|
||||||
|
editable_anchors.append(anchor)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"err '{bm_name}' e: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 无匹配书签时直接返回
|
||||||
if not editable_anchors:
|
if not editable_anchors:
|
||||||
print("文档中无可编辑控件")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# 计算有效索引(循环逻辑)
|
# 计算有效索引(循环逻辑)
|
||||||
total = len(editable_anchors)
|
total = len(editable_anchors)
|
||||||
effective_index = current_index % total # 此处不再报错
|
effective_index = current_index % total # 自动处理越界
|
||||||
|
|
||||||
# 定位到目标控件
|
# 定位到目标书签
|
||||||
target_anchor = editable_anchors[effective_index]
|
target_anchor = editable_anchors[effective_index]
|
||||||
view_cursor.gotoRange(target_anchor, False)
|
|
||||||
controller.select(target_anchor) # 选中控件(可选)
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 跳转到书签起始位置
|
||||||
|
view_cursor.gotoRange(target_anchor, False)
|
||||||
|
# 选中整个书签范围
|
||||||
|
controller.select(target_anchor)
|
||||||
|
|
||||||
|
# 窗口可见性处理
|
||||||
|
try:
|
||||||
|
window = controller.getFrame().getContainerWindow()
|
||||||
|
window.setVisible(True)
|
||||||
|
window.toFront()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
raise RuntimeError(f"err: {str(e)}") from e
|
||||||
|
|
||||||
|
|
||||||
g_exportedScripts = (
|
g_exportedScripts = (
|
||||||
@ -708,18 +667,8 @@ g_exportedScripts = (
|
|||||||
DeleteRow,
|
DeleteRow,
|
||||||
DeleteRowWithJSON,
|
DeleteRowWithJSON,
|
||||||
ReplaceTextAndInsertTableRow,
|
ReplaceTextAndInsertTableRow,
|
||||||
DebugCallReplace,
|
|
||||||
DebugCallReplaceList,
|
|
||||||
DebugCallInsertRow,
|
|
||||||
DebugCallDeleteRow,
|
|
||||||
DebugCallLocateBookmarkLo1,
|
|
||||||
DebugCallLocateBookmarkLo2,
|
|
||||||
DebugCallInsertBookmark,
|
|
||||||
DebugCallUpdateBookmark,
|
|
||||||
DebugCallDeleteBookmark,
|
|
||||||
ReplaceBookmarksWithControls,
|
ReplaceBookmarksWithControls,
|
||||||
ReplaceTextAndInsertTableRowWithContentControl,
|
ReplaceTextAndInsertTableRowWithContentControl,
|
||||||
DebugCallReplaceBookmarksWithControls,
|
|
||||||
SaveDocument,
|
SaveDocument,
|
||||||
NextEditableZone
|
NextEditableZone,
|
||||||
)
|
)
|
||||||
|
Loading…
Reference in New Issue
Block a user