python 處理Excel 常見問題-讀取Excel中時間,封裝函數


 1 import xlrd
 2 from xlrd import xldate_as_tuple
 3 from datetime import datetime
 4 
 5 #打印Excel表格數據類型,尋找對應的結局函數
 6 def ensure_cell_type():
 7     book = xlrd.open_workbook('example.xlsx')
 8     sheet = book.sheet_by_name('Sheet1')
 9     for row in range(sheet.nrows):
10         for col in range(sheet.ncols):
11             print(sheet.cell(row,col))
12             print('type',sheet.cell(row,col).ctype)
13 
14 #轉換Excel中時間格式,此處的類型是3
15 def tran_time_form():
16     book = xlrd.open_workbook('example.xlsx')
17     sheet = book.sheet_by_name('Sheet1')
18     for row in range(sheet.nrows):
19         for col in range(sheet.ncols):
20             value = sheet.cell(row, col).value
21             if sheet.cell(row, col).ctype == 3:
22                 date = xldate_as_tuple(sheet.cell(row, col).value, 0)
23                 print(date)
24                 value = datetime(*date)
25                 print(value)
26 
27 def main():
28     ensure_cell_type()
29     #tran_time_form()
30 
31 if __name__ == "__main__":
32     main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM