本文主要介紹xlrd模塊讀取Excel文檔的基本用法,並以一個GDP數據的文檔為例來進行操作。
1. 准備工作:
1. 安裝xlrd:pip install xlrd
2. 准備數據集:從網上找到的1952~2012年中國國內GDP的數據,數據結構如下:
2. 目標:將這份數據轉換成json格式的數據
3. 上代碼
#!/usr/bin/python
# coding:utf-8
# 用xlrd讀取Excel文件基本用法
import sys
import xlrd
import json
# 設置編碼格式
reload(sys)
sys.setdefaultencoding('utf-8')
# 1. 從Excel文件中讀取出Book對象
data = xlrd.open_workbook('./gdp_data.xls')
# print type(data)
# 輸出:<class 'xlrd.book.Book'>
# 2. 獲取sheet頁對象
# 2.1 通過sheet索引獲取
sheet1 = data.sheet_by_index(0)
# print sheet1
# 輸出:<xlrd.sheet.Sheet object at 0x7efc10319ed0>
# 2.2 通過sheet名稱獲取
sheet2 = data.sheet_by_name(u'Sheet1')
# print sheet2
# 輸出:<xlrd.sheet.Sheet object at 0x7efbfb72db10>
# 3. 獲取sheet頁的行數和列數
nrows = sheet1.nrows
ncols = sheet1.ncols
# print nrows,ncols
# 輸出:62 5
# 說明表格有62行、5列
# 4. 獲取第0行的值(是一個列表)
row_data = sheet1.row_values(0)
# print row_data
# 輸出:[u'year', u'GDP', u'first industry', u'second industry', u'third industry']
# 5. 獲取第0列的值(是一個列表)
col_data = sheet1.col_values(0)
# print col_data
# 輸出:[u'year', 1952.0, 1953.0, 1954.0, 1955.0,...]
# 6. 使用行列索引(從0開始)獲取單元格的數據
cell_A1 = sheet1.cell(0,0)
# print cell_A1
# print type(cell_A1)
# print cell_A1.value
# 輸出:
'''
text:u'year'
<class 'xlrd.sheet.Cell'>
year
'''
# 7. 應用:將Excel文件中的數據轉換成json數組
# 索引(即表頭)
idx = sheet1.row_values(0)
# 最終的數據列表
data = []
# 從第1行開始遍歷循環所有行,獲取每行的數據
for i in range(1,nrows):
row_data = sheet1.row_values(i)
# 組建每一行數據的字典
row_data_dict = {}
# 遍歷行數據的每一項,賦值進行數據字典
for j in range(len(row_data)):
item = row_data[j]
row_data_dict[idx[j]] = item
# 將年份字段轉成整形
row_data_dict['year'] = int(row_data_dict['year'])
# 將行數據字典加入到data列表中
data.append(row_data_dict)
print json.dumps(data,indent = 4)
# 輸出:
'''
[
{
"GDP": 679.0,
"second industry": 141.8,
"first industry": 342.9,
"third industry": 194.3,
"year": 1952
},
{
"GDP": 824.0,
"second industry": 192.5,
"first industry": 378.0,
"third industry": 253.5,
"year": 1953
},
{
"GDP": 859.0,
"second industry": 211.7,
"first industry": 392.0,
"third industry": 255.3,
"year": 1954
},
...
]
'''