1、關於Excel,我們都不陌生,但在開始操作之前,還是簡單的在來了解下Excel的結構,工作簿的英文是BOOK(WORKBOOK),工作表的英文是SHEET(WORKSHEET)
- 一個工作簿是一個獨立的文件
- 一個工作簿裏面可以有1個或者多個工作表
2、使用python實現對Excel文件的讀取,需要安裝xlrd模塊
3、excel數據中的sheet編號,行號,列號都是從索引0開始的
(Mac中的numbers文件可以導成Excel使用)
import xlrd
def read_xlsx(path):
wb=xlrd.open_workbook(path)
sheet_name=wb.sheet_names()#輸出所有工作蒲中的工作表
print(sheet_name)
# 通過sheet索引或者名稱獲取sheet
data_sheet=wb.sheet_by_index(0)
data_sheet1=wb.sheets()[0]
print(data_sheet)
print(data_sheet1)
# 通過sheet獲取行數
rowNum = wb.sheet_by_index(0).nrows;
# 通過sheet獲取列數
colNum = wb.sheet_by_index(0).ncols;
print(rowNum)
print(colNum)
# 獲取第一行的內容
print(data_sheet.row_values(1))
# 獲取第一列的內容
print(data_sheet.col_values(3))
# 獲取單元格內容
print(data_sheet.cell(9, 7).value)
# 獲取所有單元格內容
list = []
for i in range(rowNum):
rowlist = []
for j in range(colNum):
rowlist.append(data_sheet.cell_value(i, j))
list.append(rowlist)
# 輸出所有單元格的內容
for i in range(rowNum):
for j in range(colNum):
print(list[i][j], '\t\t', end="")
print()
#獲取數據單元格的數據類型
# python讀取excel中單元格的內容返回的有5種類型,即上面例子中的ctype:
# ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
data_ctype=data_sheet.cell(4,8).ctype
print(data_ctype)