python讀取excel,數字都是浮點型,日期格式是數字的解決辦法
阿新 • • 發佈:2017-06-23
6.2 spa 讀取excel pytho work clas odin 技術 div
excel文件內容:
讀取excel:
# coding=utf-8 import xlrd import sys reload(sys) sys.setdefaultencoding(‘utf-8‘) import traceback class excelHandle: def decode(self, filename, sheetname): try: filename = filename.decode(‘utf-8‘) sheetname = sheetname.decode(‘utf-8‘)except Exception: print traceback.print_exc() return filename, sheetname def read_excel(self, filename, sheetname): filename, sheetname = self.decode(filename, sheetname) rbook = xlrd.open_workbook(filename) sheet = rbook.sheet_by_name(sheetname) rows= sheet.nrows cols = sheet.ncols all_content = [] for i in range(rows): row_content = [] for j in range(cols): ctype = sheet.cell(i, j).ctype cell = sheet.cell_value(i, j) row_content.append(cell) all_content.append(row_content)print ‘[‘ + ‘,‘.join("‘" + str(element) + "‘" for element in row_content) + ‘]‘ return all_content if __name__ == ‘__main__‘: eh = excelHandle() filename = r‘G:\test\ctype.xls‘ sheetname = ‘Sheet1‘ eh.read_excel(filename, sheetname)
輸出:
[‘整形‘,‘175.0‘] [‘字符串‘,‘最後的騎士‘] [‘浮點型‘,‘6.23‘] [‘日期‘,‘42909.6461574‘] [‘空值‘,‘‘]
可以看到,數字一律按浮點型輸出,日期卻輸出成一串數字?!!
python讀取excel,數字都是浮點型,日期格式是數字的解決辦法