想想你在一家公司里做表格,現(xiàn)在有一個下面這樣的excel表擺在你面前,這是一個員工每個月工資的表,
現(xiàn)在假設,你要做的事情,是填充好后面幾個月每個員工的編號,并且給員工隨機生成一個2000到50000之間的隨機數(shù)作為該月的工資,能拿多少全靠天意,你為了鍛煉自己的python能力決定寫一個相關的代碼:
首先要引入庫函數(shù),要修改excel內(nèi)容首先需要有openpyxl這個庫,要生成隨機數(shù)就要有random這個庫
import openpyxl import random
我們首先提取編號:
編號是第B列
workbook=openpyxl.load_workbook('工資.xlsx') table = workbook['Sheet1'] print(table['B'])
但此時我們發(fā)現(xiàn)提取出的是cell格式的數(shù)據(jù)而不是我們常見的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)
接下來我們要將最前面的員工名稱復制到后面,假設我們已經(jīng)知道有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
這時候卻發(fā)現(xiàn)如下報錯:
這時因為我們有的格子是合并起來的
只需要將代碼改成如下形式即可:
tempi=0 for cell in table['B']: try: cell.value=IDList[tempi] except: print('') tempi=tempi+1
主要靠更改后面參數(shù),例如我想新存一個result.xlsx
workbook.save(filename = "result.xlsx")
假如你發(fā)現(xiàn),此時存儲結(jié)果編號局中了:
我想將其居左,只需將前面代碼修改為:
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表某一列內(nèi)容的詳細內(nèi)容,更多關于python修改excel的資料請關注腳本之家其它相關文章!