openpyxl 删除除列 row excel 以外的所有值

openpyxl delete all values except the column row excel

我有一个 excel:

   A      B        C             D
1  long  short  suggested_long  suggested_short
2  -2.11  5.11   #N/A           
3  -4.11  3.66   #REF!           #N/A
4  93.44  7.55   0               0
5  1256.4 966.5  563.5           #REF!

因此,long 在单元格(A1) 中,5.11 在单元格(B2) 中; 我想清除 suggested_long 和 suggested_short 中的所有值,但需要保留列名行,因为我需要在清除所有值后插入数据。那么结果应该是:

   A      B        C             D
1  long  short    
2  -2.11  5.11              
3  -4.11  3.66             
4  93.44  7.55               
5  1256.4 966.5             

我知道 openpyxl 可以这样做:

for row in ws['C1:D5']:
  for cell in row:
    cell.value = None

删除单元格中的值,但我不确定suggested_long和suggested_short中单元格值的数量。我想其他人可能有同样的问题,所以我 post 在这里,非常感谢

试试这个:

for row in ws['C2:D'+str(len(ws['D']))]:
  for cell in row:
    cell.value = None

当然,最简单的方法就是删除列并替换 headers:

ws.delete_cols(3, 2)
ws["C1"] = "suggested_long"
ws["D1"] = "suggested_short"

否则使用ws.iter_rows(min_row=2, min_col=3)