日常工作中會遇到Excel的讀寫問題。我們可以使用xlwt 模塊將數據寫入Excel表格,使用xlrd 模塊從Excel讀取數據,使用xlutils模塊和xlrd模塊結合對Excel數據進行修改。下面介紹如何實現使用python對Excel進行讀寫修改操作。
1、對Excel的寫操作:
import xlwt
book = xlwt.Workbook() #新建一個excel
sheet = book.add_sheet('sheet1') #添加一個sheet頁
sheet.write(0,0,'姓名') #Excel第一行第一列寫入姓名
sheet.write(0,1,'性別') #Excel第一行第二列寫入性別
sheet.write(0,2,'年齡') #Excel第一行第三列寫入年齡
book.save('stu.xls') #微軟的office不能用xlsx結尾的,wps隨意
舉例:從二維列表中讀取數據,寫入到excel中。
stus = [
['姓名','年齡','性別','分數'],
['mary', 20, '女', 89.9],
['mary', 20, '女', 89.9],
['mary', 20, '女', 89.9],
['mary', 20, '女', 89.9]]
book = xlwt.Workbook() #新建一個excel
sheet = book.add_sheet('sheet1') #添加一個sheet頁
raw = 0#控制行的
for stu in stus:
col = 0 #控制列
for s in stu:
sheet.write(raw,col,s)
col+=1
raw+=1
book.save('kkk.xls')
2、對Excel的讀操作
import xlrd
book = xlrd.open_workbook('stu.xls') #打開一個excel
sheet = book.sheet_by_index(0) #根據順序獲取sheet
sheet2 = book.sheet_by_name('sheet1') #根據sheet頁名字獲取sheet
print(sheet.cell(0,0).value) #指定行和列獲取數據
print(sheet.ncols) #獲取excel里面有多少列
print(sheet.nrows) #獲取excel里面有多少行
sheet.row_values(1)#取第幾行的數據
print(sheet.col_values(1)) #取第幾列的數據
for i in range(sheet.nrows): # 0 1 2 3 4 5
print(sheet.row_values(i)) #取第幾行的數據
3、對Excel修改操作
from xlutils.copy import copy #從xlutils模塊導入copy
import xlrd
book1 = xlrd.open_workbook('stu.xls') #得到Excel文件的book對象,實例化對象
book2 = copy(book1) #拷貝一份原來的excel
sheet = book2.get_sheet(0) #獲取第幾個sheet頁
sheet.write(1,3,0) #對拷貝的excel第2行,第4列數據為0
sheet.write(1,0,'小黑') #對拷貝的excel第2行,第1列數據為小黑
book2.save('stu.xls') #保存修改后excel
