簡體   English   中英

用 openpyxl 用空白替換單元格值的一部分

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM