![](/img/trans.png)
[英]How to delete rows in Excel if cells in specific column are blank using python openpyxl?
[英]How to move specific cells in an excel file to a new column with openpyxl in python
我正在嘗試將一些特定的單元格移動到指定位置。 如圖所示,想將單元格 D3 中的數據移動到 E2,D5 到 E4,......等等。 用 openpyxl 可行嗎? 任何建議將不勝感激! 點擊查看圖片
這是我到目前為止得到的。 按說它奏效了。
wb=xl.load_workbook(datafile)
ws=wb['Sheet1']
#insert a new column #5
ws.insert_cols(idx=5,amount=1)
wb.save(datafile)
mr=ws.max_row
#move cells
for i in range (1,mr+1):
v=ws.cell(row = i+1,column=4)
ws.cell(row=i,column =5).value=v.value
wb.save(datafile)
wb.close
謝謝您的幫助。
我修改了代碼並且效果很好。 然后我想刪除不需要的行,但沒有用。 看起來它進入了一個無限循環。 代碼顯示在這里。 我做錯了什么?
wb=xl.load_workbook(datafile)
ws=wb['Sheet1']
#insert a new column #5
ws.insert_cols(idx=5,amount=1)
#Calculate total number of rows
mr=ws.max_row
#move cells
for i in range (2,mr,2):
ws.cell(row=i,column=5).value=ws.cell(row=i+1,column=4).value
#delete unwanted rows
for i in range (2,mr,2):
ws.delete_rows(idx=i+1,amount=1)
wb.save(datafile)
這是一個很好的努力。
這里有一些注釋可以提供幫助以及如何跳過一行。
要跳過行,您可以在范圍內設置步進。 步進是范圍參數中的最后一個數字。 所以
range(2, mr, 2)
表示“i”從 2 開始,以 2 為增量增加到最大值 [ws.max_row]。
在這種情況下,因為最大值是 7,所以 i 將是 2、4 和 6
...
wb = xl.load_workbook(datafile)
ws = wb['Sheet1']
# insert a new column #5
ws.insert_cols(idx=5, amount=1)
# wb.save(datafile) # <--- not necessary just save at the end
mr = ws.max_row
# move cells
# Move and delete the rows by making the changes from the bottom up
for i in reversed(range(2,mr,2)):
ws.cell(row=i, column=5).value = ws.cell(row=i + 1, column=4).value
ws.delete_rows(idx=i + 1, amount=1)
wb.save(datafile)
# wb.close # <-- Not needed, should have brackets anyway
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.