[英]Replace part of a cell value with blank with openpyxl
我有一個電子表格,其中Column A
有一個計算機名稱列表, domain\\
在計算機名稱之前。 我正在嘗試使用openpyxl
刪除domain\\
並只保留計算機名稱。 這是我嘗試過的代碼。 沒有錯誤,但是腳本不會更改電子表格上的任何內容。
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')
最簡單的方法是用修剪過的字符串替換單元格值。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.