我有一個電子表格,其中Column A有一個計算機名稱列表,domain\前面有計算機名稱。我正在嘗試使用openpyxl刪除domain\并僅保留計算機名稱。這是我嘗試過的代碼。沒有錯誤,但是腳本不會更改電子表格上的任何內(nèi)容。import openpyxl excelFile = openpyxl.load_workbook('C:\Users\user1\Documents\file.xlsx') sheet1 = excelFile.get_sheet_by_name('Sheet1') currentRow = 1 for eachRow in sheet1.iter_rows(): if sheet1.cell(row=currentRow, column=1).value == "'domain\'": sheet1.cell(row=currentRow, column=1).value = "" currentRow += 1 excelFile.save('C:\Users\user1\Documents\file.xlsx')
1 回答

ITMISS
TA貢獻1871條經(jīng)驗 獲得超8個贊
最簡單的方法是用修剪過的字符串替換單元格值。
import openpyxl
filename = r'C:\Users\user1\Documents\file.xlsx'
excelFile = openpyxl.load_workbook(filename)
sheet1 = excelFile.active
for row in sheet1.iter_rows(min_col=1, max_col=1):
for cell in row:
if 'domain\\' in cell.value:
cell.value = cell.value[7:] #This will replace the cell value with a trimmed string
excelFile.save(filename)
添加回答
舉報
0/150
提交
取消