第一步: 先下載一個xlrd 包
# pip install xlrd
import xlrd from datetime import date, datetime file = '學生信息表.xlsx' def read_excel(): wb = xlrd.open_workbook(filename=file) # 打開文件 print(wb.sheet_names()) # 查看所有表的表格名字,如(Sheet1) sheet1 = wb.sheet_by_index(0) # 通過索引獲取表格 sheet2 = wb.sheet_by_name('Sheet1') # 通過表格底下的名,獲取表格 print(sheet1, sheet2) print(sheet1.name, sheet1.nrows, sheet1.ncols) # 獲取表格名,行數和列數 print(sheet2.name, sheet2.nrows, sheet2.ncols) rows = sheet1.row_values(2, 2) # 先獲取第n行數據然后從第i列起一直到列的末尾的內容,只寫一個數表示該行所有內容,因為源碼默認列=None cols = sheet1.col_values(2, 1) # 先獲取第n列數據然后從第i行起一直到行的末尾的內容,只寫一個數表示該行所有內容,因為源碼默認列=None print(rows, cols) print(sheet1.cell(2, 5).ctype) # 獲取n行i列的內容 # 對於excel 表格中返回的內容有5中類型 # ctype:0 empty ,1:string, 2:number 3:date, 4:boolean, 5:error 即 date 的 ctype =3時,使用xlrd的xldate_as_tuple來處理date格式. date_value = xlrd.xldate_as_tuple(sheet1.cell_value(2, 5), wb.datemode) # 此時date_value就是 date的數據了. print(date_value) print(date(*date_value[:3])) print(date(*date_value[:3]).strftime('%Y/%m/%d')) print(sheet1.merged_cells)
