Python中Excel操做

在Python中,操做excel有三種方式,分別爲讀取excel,寫excel,修改excel
讀excel
讀excel,是使用的xlrd模塊,在Python內置模塊中,沒有包含,須要本身手動安裝
安裝過程我就不詳細介紹了,能夠經過pip install xlrd方式直接安裝好python

導入模塊app

import xlrd

 

在讀excel模塊中,經常使用的函數以下
首先,打開一個excel函數

book = xlrd.open_workbook('user.xls')	#打開一個excel文件 

 

獲取sheet頁,有三種方法,以下excel

sheet = book.sheet_by_index(0)	#經過索引順序得到sheet頁
sheet1= book.sheets()[0]	#經過索引順序得到sheet頁
sheet2= book.sheet_by_name('sheet1')	#經過sheet頁名稱得到

 

excel經常使用的讀操做以下blog

print(sheet.cell(0,0).value) #指定sheet頁面裏邊的行和列的數據
print(sheet.cell(0,2).value) #指定sheet頁面裏邊的行和列的數據
print(sheet2.row_values(0)) #獲取指定某行的數據
print(sheet2.col_values(0)) #獲取指定某列的數據
print(sheet.nrows) #獲取到excel裏邊總共有多少行
print(sheet.ncols)	#獲取到excel裏邊總共多少列
#循環讀取每行數據,循環獲得的是將每行數據,放到一個list中
for i in range(sheet.nrows): #循環獲取到每行數據
print(sheet.row_values(i))

  

寫excel
寫excel,是使用的xlwd模塊,在Python內置模塊中,沒有包含,須要本身手動安裝索引

導入模塊ip

import xlwd

  

在寫excel模塊中,經常使用的函數以下
首先,新建一個excelget

book = xlwt.Workbook() #新建一個excel

  

而後再excel 中添加一個sheet頁it

sheet=book.add_sheet('sheet1') #添加一個sheet頁面

  

而後再excel中進行寫操做pip

sheet.write(0,0,'姓名') #行、列、寫入的內容
sheet.write(0,1,'年齡')
sheet.write(0,2,'性別')

  

循環寫入

list = ['小明','小紅','小黑']
[sheet.write(0,i,j) for i,j in enumerate(list)]	#列表生成式,先循環list,而後sheet.write循環寫入內容
#enumerate函數是將i從0開始自動加1,而後獲取list中的每一個元素

  

最後編輯完成以後,保存excel,記住,保存excel 的時候,必定要用.xls結尾

book.save('stu.xls') #結尾必定要用.xls

  

修改excel
修改excel,是使用的xlutils模塊,在Python內置模塊中,沒有包含,須要本身手動安裝
首先在使用xlutils模塊的以前,先用xlrd模塊,打開一個excel

導入模塊

import xlrd	#導入xlrd模塊,打卡一個excel
from xlutils import copy	#導入xlutils中的copy函數

  

讀取excel

book = xlrd.open_workbook('user.xls')	#先用xlrd模塊,打開一個excel

  

而後使用xlutils模塊中的copy函數,複製一個excel出來

new_book = copy.copy(book)	#經過xlutils這個模塊裏面copy方法,複製一份excel

  

獲取sheet頁

sheet = new_book.get_sheet(0) #獲取sheet頁

  

而後進行寫操做

lis = ['編號','名字','性別','年齡','地址','班級','手機號','金幣']
for col,filed in enumerate(lis):
sheet.write(0,col,filed)

  

最後保存excel,記住,保存excel 的時候,必定要用.xls結尾

new_book.save('app_student.xls')
相關文章
相關標籤/搜索