wb=openpyxl.load_workbook('ttt.xlsx') #打開(kāi)excel文件
print(wb.get_sheet_names()) #獲取工作簿所有工作表名
sheet=wb.get_sheet_by_name('Sheet1') #獲取工作表
print(sheet.title)
sheet02=wb.get_active_sheet() #獲取活動(dòng)的工作表
print(sheet02.title)
(2)操作單元格
print(sheet['A1'].value) #獲取單元格A1值
print(sheet['A1'].column) #獲取單元格列值
print(sheet['A1'].row) #獲取單元格行號(hào)
print(sheet.cell(row=1,column=1).value) #獲取單元格A1值,column與row依然可用
for i in range(1,4,1):
print(sheet.cell(row=i,column=1).value) #更加方便實(shí)用
print(sheet.max_column) #獲取最大列數(shù)
print(sheet.max_row) #獲取最大行數(shù)
(3)讀取excel文件
#wbname==即文件名稱,sheetname==工作表名稱,可以為空,若為空默認(rèn)第一個(gè)工作表
def readwb(wbname,sheetname):
wb=openpyxl.load_workbook(filename=wbname,read_only=True)
if (sheetname==""):
ws=wb.active
else:
ws=wb[sheetname]
data=[]
for row in ws.rows:
list=[]
for cell in row:
aa=str(cell.value)
if (aa==""):
aa="1"
list.append(aa)
data.append(list)
print (wbname +"-"+sheetname+"- 已成功讀取")
return data
(4)新建excel,并寫(xiě)入數(shù)據(jù)
#新建excel
def creatwb(wbname):
wb=openpyxl.Workbook()
wb.save(filename=wbname)
print ("新建Excel:"+wbname+"成功")
# 寫(xiě)入excel文件中 date 數(shù)據(jù),date是list數(shù)據(jù)類型, fields 表頭
def savetoexcel(data,fields,sheetname,wbname):
print("寫(xiě)入excel:")
wb=openpyxl.load_workbook(filename=wbname)
sheet=wb.active
sheet.title=sheetname
field=1
for field in range(1,len(fields)+1): # 寫(xiě)入表頭
_=sheet.cell(row=1,column=field,value=str(fields[field-1]))
row1=1
col1=0
for row1 in range(2,len(data)+2): # 寫(xiě)入數(shù)據(jù)
for col1 in range(1,len(data[row1-2])+1):
_=sheet.cell(row=row1,column=col1,value=str(data[row1-2][col1-1]))
wb.save(filename=wbname)
print("保存成功")