xlrd是Python常用于读取excel文件的库:
=============================================================================================
1.例如读取下面这张表
=================================================================================================================
2.读取文件的方式:
# 创建一个excel对象:
excel = xlrd.open_workbook(filename)
# 返回excel一个名为“Sheet1“的sheet页对象
data = excel.sheet_by_name("Sheet1")
# 读取行数
rows = data.nrows
# 读取第row行的值
years = data.row_values(row)
# 读取列数
cols = data.col
# 读取第col列
provinces = data.col_values(col)
=============================================================================================================
3.具体代码
# 创建一个DataInit类,文件名:GetFile.py
#! -*- coding:utf-8 -*-
import os
import xlrd
class DataInit(object):
def __init__(self, row=0, col=0):
self.name = "DATA.xlsx"
self.path = os.getcwd()
self.provinces = list()
self.years = list()
self.data = None
self.row = row
self.col = col
def getfile(self, row, col):
filename = self.path+"\\"+self.name
# 创建一个excel的对象
excel = xlrd.open_workbook(filename)
# 返回excel一个名为“Sheet1“的sheet页对象
self.data = excel.sheet_by_name("Sheet1")
# 读取行数
rows = self.data.nrows
# 读取表头即第0行的值
self.years = self.data.row_values(row)
# print("统计年限:", self.years)
# 读取列数
cols = self.data.col
# 读取列
self.provinces = self.data.col_values(col)
# print("统计全国各省和直辖市:", self.provinces)
return self.data
@staticmethod
def get_row(data, row):
row_value = data.row_values(row)
return row_value
@staticmethod
def get_col(data, col):
row_value = data.col_values(col)
return row_value
def data_init(self, data, row, col):
city = self.get_row(data, col)
years = self.get_col(data, row)
return city, years
============================================================================================================
# 实现文件读取,文件名:readfile.py #! -*- coding:utf-8 -*—
from lib.GetFile import DataInit
def draw():
data_init = DataInit()
data = data_init.getfile(1,1)
city, year = data_init.data_init(data, 1, 1)
print(city)
print(year )
if __name__ == "__main__":
draw()
4.结果