轉載自:http://blog.csdn.net/orangleliu/
有個excle表格需要做一些過濾然後寫入數據庫中,但是日期類型的cell取出來是個數字,於是查詢了下解決的辦法。
基本的代碼結構
- data = xlrd.open_workbook(EXCEL_PATH)
- table = data.sheet_by_index(0)
- lines = table.nrows
- cols = table.ncols
- print u'The total line is %s, cols is %s'%(lines, cols)
讀取某個單元格:
- table.cell(x, y).value
y:列
行,列都是從0開始
* 時間類型的轉換,把excel中時間轉成Python 時間(兩種方式)
excel某個單元格 2014/7/8
- xlrd.xldate_as_tuple(table.cell(2,2).value, 0) #轉化爲元組形式
- (2014, 7, 8, 0, 0, 0)
- xlrd.xldate.xldate_as_datetime(table.cell(2,2).value, 1) #直接轉化爲datetime對象
- datetime.datetime(2018, 7, 9, 0, 0)
- table.cell(2,2).value #沒有轉化
- 41828.0
源碼查看:
- # @param xldate The Excel number
- # @param datemode 0: 1900-based, 1: 1904-based.
- xldate_as_tuple(xldate, datemode)
datemode 有2個選項基本我們都會使用1900爲基礎的時間戳
- ##
- # Convert an Excel date/time number into a datetime.datetime object.
- #
- # @param xldate The Excel number
- # @param datemode 0: 1900-based, 1: 1904-based.
- #
- # @return a datetime.datetime() object.
- #
- def xldate_as_datetime(xldate, datemode)
當然這兩個函數都有相應的逆函數,把python類型變成相應的excle時間類型。