我是python的新手,我需要编写一个程序将单元格中的字母更改为相反的形式,并且还需要知道列中名称的数量以及名称列表所在的行,以便它可以更改所有的名称。该代码是为我能够更改名称,而不是看名字列表由于隐私的原因。如果有人想知道,我目前正在使用Pycharm和Openpyxl。这张图显示了它应该是什么样子的前后。我已经做了几次尝试,但在那之后,我似乎就是找不到任何关于如何改变字母表的想法。我也尝试了替换(replacement = {'Danial‘= 'Wzmrzo'})函数,但我需要查看姓名列表,然后才能更改字母。
import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter
print("Type the file name:")
DF = input()
wb = load_workbook(DF + '.xlsx')
print("Sheet Name:")
sht = input()
ws = wb[sht]
NC = str(input("Where is the Name Column?"))
column = ws[ NC ]
column_list = [column[x].value for x in range(len(column))]
print(column_list)
wb.save(DF + '.xlsx')
之前
之后
发布于 2021-11-23 05:15:38
警告:我不太熟悉openpyxl以及它们是如何访问行/列的,但在过去的几年里,它似乎发生了很大的变化。因此,这应该会给你一个如何让它工作的想法,但可能不会完全像你写的那样工作,这取决于你的版本。
要查找名称列,可以使用
name_col = False
# loop along the top row looking for "Name"
for i,x in enumerate(ws.iter_cols(max_row=1)):
if x[0].value == "Name":
name_col = i + 1 # enumerate is 0 indexed, excel rows/cols are 1 indexed
break
if name_col:
# insert name changing code here
else:
print("'Name' column not found.")
更改您可以使用的名称(在上面的代码中插入此代码)
# loop down name column
for i,x in enumerate(ws.iter_rows(min_col = name_col, max_col = name_col)):
# we need to skip the header row so
if i == 0:
continue
name = x[0].value
new_name = ""
for c in name:
# ord() gets the ASCII value of the char, manipulates it to be the opposite then uses chr() to get back the character
if ord(c) > 90:
new_c = chr(25 - (ord(c) - 97) + 97)
else:
new_c = chr(25 - (ord(c) - 65) + 65)
new_name.append(new_c)
ws.cell(row=i+1, column=name_col).value = new_name # enumerate is 0 indexed, excel rows/cols are 1 indexed hence i+1
https://stackoverflow.com/questions/70081082
复制