由於工作需要,需要對 Excel 數據進行一些預處理,所以隨便寫了一點 python 處理 Excel 的方法。。。
一、導入相應庫
xlrd:讀入Excel
xlwt:寫入Excel
安裝命令如下:
pip install xlrd
pip install xlwt
二、讀入Excel
1. Excel表格內容
下圖分別爲 test.xlsx 的 sheet1 和 sheet2 數據:
2. 代碼 code
# -*- coding: utf-8 -*-
import xlrd
#如果處理日期時間,import datetime
#from datetime import date,datetime
__author__ = 'Binchasing'
f1_name = 'test.xlsx' #文件名
f1 = xlrd.open_workbook(f1_name) #打開文件
print f1.sheet_names() #打印所有Sheet名字
sheet1_name = f1.sheet_names()[0] #Sheet1名字
# 根據索引or名稱獲取sheet內容
sheet1 = f1.sheet_by_index(0) #獲取sheet1內容
sheet2 = f1.sheet_by_name('Sheet2') #獲取sheet2內容
# 分別顯示sheet名字(.name),總行數(.nrows),總列數(.ncols)
print sheet1.name, sheet1.nrows, sheet1.ncols
print sheet2.name, sheet2.nrows, sheet2.ncols
#獲取行or列內容
rows = sheet2.row_values(1) # 獲取第2行內容
print rows
cols = sheet2.col_values(2) # 獲取第3列內容
print cols
# 不同方式獲取單元格內容(顯示第3行第1列)
print sheet2.cell(2,0).value.encode('utf-8')
print sheet2.cell_value(2,0).encode('utf-8')
print sheet2.row(2)[0].value.encode('utf-8')
# 獲取單元格內容的數據類型
#python讀取excel中單元格的內容返回的有5種類型ctype:
#ctype : 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
print sheet2.cell(1,0).ctype
3. 輸出 output
[u'Sheet1', u'Sheet2']
Sheet1 12 5
Sheet2 16 3
[u'\u5e7f\u4e1c', 0.15358814900011789, 0.1531192108472316]
[u'\u6536\u8ba2\u5546\u54c1\u6570\u91cf', 0.1531192108472316, 0.09575012248494419, 0.0662265835916449, 0.06478424965797056, 0.06471695832224465, 0.043246131578273374, 0.04324150395611867, 0.04248287305338446, 0.04106440576789475, 0.0396537204291989, 0.036066907296305406, 0.03317248513899366, 0.03194612025991795, 0.028247799159356213, 0.024346356684779705]
北京
北京
北京
1
[Finished in 0.1s]
三、寫入Excel
。。。。之後再更新