python實(shí)現(xiàn)對(duì)excel表格不同文件形式的讀取
我最近在用 pycharm 讀取excel數(shù)據(jù)出現(xiàn)幾個(gè)莫名其妙的問題, 我解決問題之后,覺得還是把這些坑都寫清楚,方便 python 的初學(xué)者。
?用xlrd庫(kù)讀取.xls文件
xlrd庫(kù)只能讀取.xls文件 是因?yàn)閤lrd在高版本中該庫(kù)認(rèn)為.xlsx文件存在漏洞
?用庫(kù)openpyxl讀取.xlsx文件
用庫(kù)openpyxl是不能讀取.xls文件的
?'.xls文件的讀取'文章來源:http://www.zghlxwxcb.cn/news/detail-537670.html
# xlrd庫(kù)只能讀取.xls文件 是因?yàn)閤lrd在目前的版本中該庫(kù).xlsx文件存在漏洞
def excelread(catalog, path):
# 獲取文件路徑
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, catalog, path)
data = xlrd.open_workbook(file_path)
table = data.sheets()[0]
nrows = table.nrows # 行數(shù)
ncols = table.ncols # 列數(shù)
datamatrix = np.zeros((nrows - 1, ncols - 1)) # 減去第一列
for x in range(ncols - 1):
cols = table.col_values(x + 1) # 索引從1開始 從excel第二行開始 減去excel左側(cè)目錄
datamatrix[:, x] = cols[1:] # 把數(shù)據(jù)進(jìn)行存儲(chǔ) 減去excel上側(cè)目錄
return datamatrix
m = excelread('files', 'zz.xls')
'.xlsx文件的讀取'?文章來源地址http://www.zghlxwxcb.cn/news/detail-537670.html
# .xlsx文件 選用庫(kù)openpyxl讀取 注意該庫(kù)不能讀取.xls文件
def excelread2(catalog, path):
# 獲取文件路徑
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, catalog, path)
wb = load_workbook(file_path)
sheet = wb.worksheets[0]
nrows = sheet.max_row # 行數(shù)
ncols = sheet.max_column # 列數(shù)
datamatrix = np.zeros((nrows - 1, ncols - 1)) # 減去第一列
index = 0
for row in sheet.iter_rows(min_row=2):
cell_list = row[1:]
text_list = []
for cell in cell_list:
if cell.value is None:
cell.value = float('inf')
text_list.append(cell.value)
# text_array = np.array(text_list) # 列表轉(zhuǎn)數(shù)組
text_mat = np.mat(text_list) # 數(shù)組轉(zhuǎn)矩陣
# print(text_mat)
datamatrix[index, :] = text_mat
index += 1
return datamatrix
m = excelread2('files', 'zz.xls')
到了這里,關(guān)于【python讀取excel文件保存為矩陣形式】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!