fix: insert table error

This commit is contained in:
zzs 2025-03-24 15:55:55 +08:00
parent 6a853a9e61
commit d959e6fe14

View File

@ -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)}")