1.讀取數據整理成列表,可以兼容表格里日期,字符串等字符,詳細請看代碼:
def get(self, sheetname,data_count): #接收兩個值,第一個是表單名稱,第二個是從第幾行還是讀
workbook = xlrd.open_workbook(self.file) #文件名以及路徑,如果路徑或者文件名有中文給前面加一個r拜師原生字符。
sheet = workbook.sheet_by_name(sheetname) # 通過名稱獲取,讀取第一個接收的表格
nrows = sheet.nrows # 獲取該sheet中的有效行數
first_row_values = sheet.row_values(1) # 去讀表格第一行數據,如果是字典模式可以當做key使用,列表可用戶那單元格數據判斷使用
list_all = []
num = data_count #從表格第幾行開始讀取
for row_num in range(1, nrows): # 循環根據拿到的行數循環多少次,拿完為止
if row_num ==2:
continue
row_values = sheet.row_values(row_num) #返回由該行中所有單元格的數據組成的列表
if row_values:
str_obj = []
for i in range(len(first_row_values)): #循環取單元格里的值
ctype = sheet.cell(num, i).ctype #返回單元格對象
cell = sheet.cell_value(num, i) #返回單元格中的數據
if ctype == 2 and cell % 1 == 0.0: # ctype為2且為浮點
cell = int(cell) # 浮點轉成整型
cell = str(cell) # 轉成整型后再轉成字符串,如果想要整型就去掉該行
elif ctype == 3:
date = datetime(*xldate_as_tuple(cell, 0))
cell = date.strftime('%Y/%m/%d %H:%M:%S')
elif ctype == 4:
cell = True if cell == 1 else False
str_obj.append(cell)
list_all.append(str_obj)
num = num + 1
return list_all
2.讀取數據整理成字典,(num=1,讀取第一行作為字典key使用,索引從0開始計算)可以兼容表格里日期,字符串等字符,詳細請看代碼:
def get(self, sheetname): #接收兩個值,第一個是表單名稱,第二個是從第幾行還是讀
workbook = xlrd.open_workbook(self.file) #文件名以及路徑,如果路徑或者文件名有中文給前面加一個r拜師原生字符。
sheet = workbook.sheet_by_name(sheetname) # 通過名稱獲取,讀取第一個接收的表格
nrows = sheet.nrows # 獲取該sheet中的有效行數
first_row_values = sheet.row_values(1) # 去讀表格第一行數據,如果是字典模式可以當做key使用,列表可用戶那單元格數據判斷使用
list_all = []
num = 1 #讀取的第一行用作字典的key使用
for row_num in range(1, nrows): # 循環根據拿到的行數循環多少次,拿完為止
if row_num ==2:
continue
row_values = sheet.row_values(row_num) #返回由該行中所有單元格的數據組成的列表
if row_values:
str_obj = {}
for i in range(len(first_row_values)): #循環取單元格里的值
ctype = sheet.cell(num, i).ctype #返回單元格對象
cell = sheet.cell_value(num, i) #返回單元格中的數據
if ctype == 2 and cell % 1 == 0.0: # ctype為2且為浮點
cell = int(cell) # 浮點轉成整型
cell = str(cell) # 轉成整型后再轉成字符串,如果想要整型就去掉該行
elif ctype == 3:
date = datetime(*xldate_as_tuple(cell, 0))
cell = date.strftime('%Y/%m/%d %H:%M:%S')
elif ctype == 4:
cell = True if cell == 1 else False
str_obj[first_row_values[i]] = cell
list_all.append(str_obj)
num = num + 1
return list_all
3.讀取給定列數,如讀取該表中第3列~5列
def read_ncols(self, sheetname, ncols, n=1, num=1000): # i,sheet索引
ExcelFile = xlrd.open_workbook(self.file)
table = ExcelFile.sheet_by_name(sheetname)
nrows = table.nrows # 行數
ncols = table.ncols # 列數
j = 0 # 循環次數
for row in range(1, nrows):
j += 1
line = []
if self.tag == 'True':
for col in range(0, ncols):
line.append(table.cell(row, col).value)
yield line
elif self.tag == 'False':
if j >= n and j < n + num:
for col in range(0, ncols):
line.append(table.cell(row, col).value)
yield line
