这篇文章主要介绍了如何使用python修改excel表某一列内容的操作方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
想想你在一家公司里做表格,现在有一个下面这样的excel表摆在你面前,这是一个员工每个月工资的表,
现在假设,你要做的事情,是填充好后面几个月每个员工的编号,并且给员工随机生成一个2000到50000之间的随机数作为该月的工资,能拿多少全靠天意,你为了锻炼自己的python能力决定写一个相关的代码:
首先要引入库函数,要修改excel内容首先需要有openpyxl这个库,要生成随机数就要有random这个库
import openpyxl
import random
我们首先提取编号:
编号是第B列
workbook=openpyxl.load_workbook('工资.xlsx')
table = workbook['Sheet1']
print(table['B'])
但此时我们发现提取出的是cell格式的数据而不是我们常见的list格式,我们可以通过以下方式获得list格式:
def cell2List(CELL):
LIST=[]
for cell in CELL:
LIST.append(cell.value)
return LIST
IDList=cell2List(table['B'])
print(IDList)
接下来我们要找到 ‘工作编号' 这几个字的位置
def get_location_in_list(x, target):
step = -1
items = list()
for i in range(x.count(target)):
y = x[step + 1:].index(target)
step = step + y + 1
items.append(step)
return items
IDPos=get_location_in_list(IDList, '工作编号')
print(IDPos)
接下来我们要将最前面的员工名称复制到后面,假设我们已经知道有5个人,且知道小标题占两个格子(‘工作编号' 这几个字后面跟着' ')
那么编写如下代码:
staffNum=5
for i in range(0,len(IDPos)):
IDList[IDPos[i]+1:IDPos[i]+2+staffNum]=IDList[IDPos[0]+1:IDPos[0]+2+staffNum]
print(IDList)
这时候我们只需要将只赋回cell即可:
tempi=0
for cell in table['B']:
cell.value=IDList[tempi]
tempi=tempi+1
这时候却发现如下报错:
这时因为我们有的格子是合并起来的
只需要将代码改成如下形式即可:
tempi=0
for cell in table['B']:
try:
cell.value=IDList[tempi]
except:
print('')
tempi=tempi+1
主要靠更改后面参数,例如我想新存一个result.xlsx
workbook.save(filename = "result.xlsx")
假如你发现,此时存储结果编号局中了:
我想将其居左,只需将前面代码修改为:
tempi=0
for cell in table['B']:
try:
cell.value=IDList[tempi]
cell.alignment = openpyxl.styles.Alignment(horizontal='left', vertical='center')
except:
print('')
tempi=tempi+1
与前面类似,较为简单,建议看完整代码自己领悟嗷
import openpyxl
import random
def cell2List(CELL):
LIST=[]
for cell in CELL:
LIST.append(cell.value)
return LIST
def get_location_in_list(x, target):
step = -1
items = list()
for i in range(x.count(target)):
y = x[step + 1:].index(target)
step = step + y + 1
items.append(step)
return items
workbook=openpyxl.load_workbook('工资.xlsx')
table = workbook['Sheet1']
IDList=cell2List(table['B'])
salaryList=cell2List(table['C'])
IDPos=get_location_in_list(IDList, '工作编号')
staffNum=5
for i in range(0,len(IDPos)):
IDList[IDPos[i]+1:IDPos[i]+2+staffNum]=IDList[IDPos[0]+1:IDPos[0]+2+staffNum]
for j in range(IDPos[i]+1,IDPos[i]+2+staffNum):
salaryList[j]=1
# tempi=0
# for cell in table['B']:
# cell.value=IDList[tempi]
# tempi=tempi+1
tempi=0
for cell in table['B']:
try:
cell.value=IDList[tempi]
cell.alignment = openpyxl.styles.Alignment(horizontal='left', vertical='center')
except:
print('')
tempi=tempi+1
tempi=0
for cell in table['C']:
try:
if salaryList[tempi]==1:
cell.value=random.randint(2000,50000)
except:
print('')
tempi=tempi+1
workbook.save(filename = "result.xlsx")
效果:
感谢你能够认真阅读完这篇文章,希望小编分享的“如何使用python修改excel表某一列内容的操作方法”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。