標籤:pos rom += from 開始 excel 取數 value office
python操作excel使用xlrd、xlwt和xlutils模組。xlrd模組是讀取excel的,xlwt模組是寫excel的,xlutils是用來修改excel的
一、python 讀取excel
import xlrd
book = xlrd.open_workbook(‘all_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): # 擷取excel中有多少行
print(sheet.row_values(i)) #取第幾行的資料
二、python 操作excel
import xlwt
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頁
sheet.write(0,0,‘姓名‘)#一行一行寫入
# sheet.write(0,1,‘性別‘)
# sheet.write(0,2,‘年齡‘)
# book.save(‘stu.xls‘) #微軟的office不能用xlsx結尾的,wps隨意
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‘)#微軟的office不能用xlsx結尾的,wps隨意
三、python 修改excel
from xlutils.copy import copy
import xlrd
book1 = xlrd.open_workbook(‘stu.xls‘)
book2 = copy(book1) #拷貝一份原來的excel
sheet = book2.get_sheet(0) #擷取第幾個sheet頁
sheet.write(1,3,0)#寫入需要修改的行、列及修改後的值
sheet.write(1,0,‘小黑‘)
book2.save(‘stu.xls‘)
Python 操作excel