From d959e6fe141581caa969b2f4ab21f305c9e93354 Mon Sep 17 00:00:00 2001 From: zzs Date: Mon, 24 Mar 2025 15:55:55 +0800 Subject: [PATCH] fix: insert table error --- BookmarkOP.py | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/BookmarkOP.py b/BookmarkOP.py index 1a8d0d1..ecabe08 100644 --- a/BookmarkOP.py +++ b/BookmarkOP.py @@ -209,16 +209,40 @@ def InsertRow(location_bookmark_name, data, start_row_index=-1): raise ValueError(f"数据列数不匹配,表格有 {col_count} 列") try: - for _ in range(len(data)): - if start_row_index > 0 & start_row_index < row_count: - handle_table.getRows().insertByIndex(start_row_index, 1) - else: - handle_table.getRows().insertByIndex(row_count, 1) + # for _ in range(len(data)): + # if start_row_index > 0 & start_row_index < row_count: + # handle_table.getRows().insertByIndex(start_row_index, 1) + # else: + # handle_table.getRows().insertByIndex(row_count, 1) - for row_idx, row_data in enumerate(data, start=row_count): - for col_idx, cell_value in enumerate(row_data): - cell = handle_table.getCellByPosition(col_idx, row_idx) - cell.setString(str(cell_value)) + # for row_idx, row_data in enumerate(data, start=row_count): + # for col_idx, cell_value in enumerate(row_data): + # cell = handle_table.getCellByPosition(col_idx, row_idx) + # cell.setString(str(cell_value)) + + # 获取需要插入的行数 + # 获取表格当前总行数 + 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)) + + except Exception as e: raise RuntimeError(f"插入行时发生错误: {str(e)}")