如何解决添加新行时如何遍历所有excel表行?
我正在使用 openpyxl 读取 excel 文件,在工作表的行中查找特定文本,在该行上方添加新行并复制一些信息。
问题如下:当我使用 worksheet.iter_rows() 时,它只迭代我最初在文档中的行数(不计入之后添加的行)。因此,某些包含 TEXT 的行超出了初始行数的范围,因此未包含在迭代中。
问题:我可以以何种方式遍历所有行,包括通过我的搜索添加的行?
for row in worksheet.iter_rows(min_row=None,max_row=None,min_col=None,max_col= None,values_only=False):
#loop through all cells in the row
for cell_text in row:
text = 'TEXT'
#check if text is in one of the cells in the row
if text == str(cell_text.value):
#get an index of a row with text
row_text = cell_text.row
#get column index with the text
column_text = cell_text.column
#insert 10 rows before the TEXT row
worksheet.insert_rows(row_text,amount=10)
#as we insert rows before the TEXT row,index of the row for new text stays the same
workcell_text1 = worksheet.cell(row_text,column_text)
#insert new text (TEXT1) to the cell
workcell_text1.value = 'TEXT1'
#move to the row with old TEXT to rename it into TEXT2
row_text2 = row_text + 10
workcell_text2 = worksheet.cell(row_text2,column_ROM)
workcell_text2.value = 'TEXT2'
#I need to copy values from 10 rows after initial TEXT and column following cell with "TEXT" to the same column of newly created 10 rows row by row
column_text +=1
for i in range(10):
row_text1 +=1
row_text2 +=1
workcell_text2 = worksheet.cell(row_text2,column_text)
new_value = workcell_text2.value
workcell_text1 = worksheet.cell(row_text2,column_text)
workcell_text1.value = new_value
book.save(excel_file)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。