这篇教程用python修改excel表某一列内容的操作方法写得很实用,希望能帮到您。 想想你在一家公司里做表格,现在有一个下面这样的excel表摆在你面前,这是一个员工每个月工资的表, 
现在假设,你要做的事情,是填充好后面几个月每个员工的编号,并且给员工随机生成一个2000到50000之间的随机数作为该月的工资,能拿多少全靠天意,你为了锻炼自己的python能力决定写一个相关的代码: 1 库引入首先要引入库函数,要修改excel内容首先需要有openpyxl这个库,要生成随机数就要有random这个库 import openpyxlimport random 2 提取cell我们首先提取编号: 编号是第B列 workbook=openpyxl.load_workbook('工资.xlsx')table = workbook['Sheet1']print(table['B']) 
3 提取List但此时我们发现提取出的是cell格式的数据而不是我们常见的list格式,我们可以通过以下方式获得list格式: def cell2List(CELL): LIST=[] for cell in CELL: LIST.append(cell.value) return LISTIDList=cell2List(table['B'])print(IDList) 
4 修改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 itemsIDPos=get_location_in_list(IDList, '工作编号')print(IDPos) 
接下来我们要将最前面的员工名称复制到后面,假设我们已经知道有5个人,且知道小标题占两个格子(‘工作编号' 这几个字后面跟着' ') 那么编写如下代码: staffNum=5for i in range(0,len(IDPos)): IDList[IDPos[i]+1:IDPos[i]+2+staffNum]=IDList[IDPos[0]+1:IDPos[0]+2+staffNum]print(IDList) 
5 修改cell值这时候我们只需要将只赋回cell即可: tempi=0for cell in table['B']: cell.value=IDList[tempi] tempi=tempi+1 这时候却发现如下报错: 
这时因为我们有的格子是合并起来的 
只需要将代码改成如下形式即可: tempi=0for cell in table['B']: try: cell.value=IDList[tempi] except: print('') tempi=tempi+1 6 存储回原EXCEL或新EXCEL主要靠更改后面参数,例如我想新存一个result.xlsx workbook.save(filename = "result.xlsx") 7 其他格式修正(居左为例)假如你发现,此时存储结果编号局中了: 
我想将其居左,只需将前面代码修改为: tempi=0for cell in table['B']: try: cell.value=IDList[tempi] cell.alignment = openpyxl.styles.Alignment(horizontal='left', vertical='center') except: print('') tempi=tempi+1 8 随机生成工资与前面类似,较为简单,建议看完整代码自己领悟嗷 9 完整代码import openpyxlimport randomdef cell2List(CELL): LIST=[] for cell in CELL: LIST.append(cell.value) return LISTdef 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 itemsworkbook=openpyxl.load_workbook('工资.xlsx')table = workbook['Sheet1']IDList=cell2List(table['B'])salaryList=cell2List(table['C'])IDPos=get_location_in_list(IDList, '工作编号')staffNum=5for 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+1tempi=0for cell in table['B']: try: cell.value=IDList[tempi] cell.alignment = openpyxl.styles.Alignment(horizontal='left', vertical='center') except: print('') tempi=tempi+1tempi=0for cell in table['C']: try: if salaryList[tempi]==1: cell.value=random.randint(2000,50000) except: print('') tempi=tempi+1workbook.save(filename = "result.xlsx") 效果: 
以上就是用python修改excel表某一列内容的详细内容,更多关于python修改excel的资料请关注51zixue.net其它相关文章! Windows安装Anaconda3的方法及使用过程详解 用Python爬取各大高校并可视化帮弟弟选大学,弟弟直呼牛X |