【python】讀取excel文件
阿新 • • 發佈:2017-10-18
python
#!/usr/bin/env python #-*- coding:utf-8 -*- #思路:就是先取出表頭,然後for循環(len(表頭數據長度)),以字典形式將表頭和數據一一插入數據庫 import xlrd def flask_OpenExcel(file=‘ceshi.xlsx‘): try: data = xlrd.open_workbook(file) return data #print data except Exception,e: print str(e) def excel_table_byindex(file = ‘ceshi.xlsx‘,colnameindex=0,by_index=0): data = flask_OpenExcel(file) #獲取表 table = data.sheets()[by_index] #獲取行數和列數 nrows = table.nrows #行數 ncols = table.ncols #列數 #表.row_values()獲取行數據,索引0代表表頭 #表.col_values()獲取列數據 colnames = table.row_values(colnameindex) #表頭行數據 list = [] for rownum in range(1,nrows): row = table.row_values(rownum) if row: app = {} for i in range(len(colnames)): app[colnames[i]] = row[i] list.append(app) return list if __name__ == "__main__": tables = excel_table_byindex() for row in tables: for key,value in row.items(): print "%s %s" %(key,value)
本文出自 “孔小發愛吃魚” 博客,謝絕轉載!
【python】讀取excel文件