首先openpyxl库没有自带的删除行列的函数,网上搜到的如下函数是错的
ws.inster_row(1)
ws.delete_row(1)
因此我们自定义一个删除行或列的函数,下面以删除行为例,删除列同理
import openpyxl
def deleterows(sheet,row_num):
for row in range(row_num, sheet.max_row):
for column in range(sheet.max_column):
sheet[row][column].value = sheet[row + 1][column].value
for cell in list(sheet.rows)[sheet.max_row - 1]:
cell.value = None
if __name__=="__main__":
wb = openpyxl.load_workbook('testbook1.xlsx')
sheet =wb.active
deleterows(sheet,1)
wb.save('testbook2.xlsx')