如何使用 openpyxl return 列中的第一个和最后一个值并将 excel 文件的标题更改为它们?
How to return first and last values in a column using openpyxl and change the title of the excel file to them?
我正在尝试更改五个文件的标题,以在该文件的列中显示第一个和最后一个值,并用“_”分隔
例如,在一列中,如果我有值 0001,0002,0003,0004,我想找到第一个和最后一个值并将文件的标题更改为 0001_0004
files=os.listdir(os.getcwd())
for file in files:
if file.endswith('.xlsx'):
print(file)
try:
wb=openpyxl.load_workbook(os.path.join(os.getcwd(),file))
print('reading workbook'+file)
ws=wb['Sheet1']
for row in range(7, ws.max_row+1):
cell = ws.cell(row = row, column = 7)
#code to change name
wb.save(os.path.join(os.getcwd(),file))
print('file title changed')
except Exception as e:
print(e)
files=os.listdir(os.getcwd())
all_xls = []
for f in files:
if f.endswith('.xlsx'):
all_xls.append(f.replace('.xls', '')
all_xls.sort()
first_file = all_xls[0]
last_file = all_xls[-1]
#Do your renaming using os.rename('src', 'dest')
这只是我能想到的一个快速解决方案,并不是最佳解决方案,您可以对其进行调整以更快地获得所需结果。
希望这对您有所帮助。
path = os.getcwd()
files = os.listdir(os.getcwd())
for filename in files:
if filename.endswith('.xlsx'):
print(filename)
wb = openpyxl.load_workbook(os.path.join(os.getcwd(),filename), data_only = True)
ws = wb['Sheet1']
final = ws.max_row
original_file = str(filename)
cell = ws['G7'].value
filenamep1 = cell
cell = ws.cell(row = final, column = 7).value
filenamep2 = cell
os.rename(original_file, path + '\' + filenamep1 + '_' + filenamep2 + '_' +
original_file)
print("All files renamed")
这就是我最终用来重命名文件的内容
我正在尝试更改五个文件的标题,以在该文件的列中显示第一个和最后一个值,并用“_”分隔
例如,在一列中,如果我有值 0001,0002,0003,0004,我想找到第一个和最后一个值并将文件的标题更改为 0001_0004
files=os.listdir(os.getcwd())
for file in files:
if file.endswith('.xlsx'):
print(file)
try:
wb=openpyxl.load_workbook(os.path.join(os.getcwd(),file))
print('reading workbook'+file)
ws=wb['Sheet1']
for row in range(7, ws.max_row+1):
cell = ws.cell(row = row, column = 7)
#code to change name
wb.save(os.path.join(os.getcwd(),file))
print('file title changed')
except Exception as e:
print(e)
files=os.listdir(os.getcwd())
all_xls = []
for f in files:
if f.endswith('.xlsx'):
all_xls.append(f.replace('.xls', '')
all_xls.sort()
first_file = all_xls[0]
last_file = all_xls[-1]
#Do your renaming using os.rename('src', 'dest')
这只是我能想到的一个快速解决方案,并不是最佳解决方案,您可以对其进行调整以更快地获得所需结果。
希望这对您有所帮助。
path = os.getcwd()
files = os.listdir(os.getcwd())
for filename in files:
if filename.endswith('.xlsx'):
print(filename)
wb = openpyxl.load_workbook(os.path.join(os.getcwd(),filename), data_only = True)
ws = wb['Sheet1']
final = ws.max_row
original_file = str(filename)
cell = ws['G7'].value
filenamep1 = cell
cell = ws.cell(row = final, column = 7).value
filenamep2 = cell
os.rename(original_file, path + '\' + filenamep1 + '_' + filenamep2 + '_' +
original_file)
print("All files renamed")
这就是我最终用来重命名文件的内容