Python 使用 xlrd
和 xlwt
兩個模塊來操做 Execl表格,分別用來讀和寫html
xlrd
讀取表格# 打開execl文件 workbook = xlrd.open_workbook(r'E:\deploy_log.xlsx') # 輸出全部sheet,輸出爲列表 print workbook.sheet_names() # 獲取 工做表(sheet)名稱 sheet1_name = workbook.sheet_names()[0] # 經過索引獲取sheet sheet1 = workbook.sheet_by_index(0) # 經過名稱獲取sheet sheet1 = workbook.sheet_by_name('first_sheet') print "sheet表名:%s, 行數:%d, 列數:%d" % (sheet1_name, sheet1.nrows, sheet1.ncols) # 獲取指定行或指定列的內容 rows = sheet1.row_values(3) cols = sheet1.col_values(4) print '第3行', rows print '第4列', cols # 獲取單元格內容 print '單元格內容', sheet1.cell(3,0).value print '單元格內容', sheet1.cell_value(3,0) print '單元格內容', sheet1.row(3)[4].value # 獲取單元格內容的數據類型 # ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error print sheet1.cell(3, 0).ctype print sheet1.cell(3, 4).ctype # 以前時間輸出爲42851.6937037,下邊進行時間轉換 print "獲取時間: ", xlrd.xldate_as_tuple(sheet1.cell_value(3,4), workbook.datemode) # 獲取合併的單元格 workbook_format = xlrd.open_workbook(r'E:\deploy_log.xlsx', formatting_info=True) sheet1_format = workbook_format.sheet_by_index(0) print sheet1.merged_cells
xlwt
寫表格官方參照:
https://pypi.python.org/pypi/...
http://xlwt.readthedocs.io/en...python
# 建立表格對象 f = xlwt.Workbook() sheet_new = f.add_sheet(u'first_sheet', cell_overwrite_ok=True) # 設置表格style style = xlwt.XFStyle() font = xlwt.Font() font.name = 'Times New Roman' font.bold = bold font.color_index = 4 font.height = 220 style.font = True # 寫數據 sheet_new.write(0, 0, 'host', style) sheet_new.write(0, 1, 'warname', style) sheet_new.write(0, 2, 'runtime', style)