您好,欢迎访问一九零五行业门户网

详解python中xlrd包的安装与处理Excel表格

一、安装xlrd
地址
下载后,使用 pip install .whl 安装即好。
查看帮助:
>>> import xlrd >>> help(xlrd) help on package xlrd: name xlrd package contents biffh book compdoc formatting formula info licences sheet timemachine xldate xlsx functions count_records(filename, outfile=<idlelib.pyshell.pseudooutputfile object at 0x0287e730>) dump(filename, outfile=<idlelib.pyshell.pseudooutputfile object at 0x0287e730>, unnumbered=false) open_workbook(filename=none, logfile=<idlelib.pyshell.pseudooutputfile object at 0x0287e730>, verbosity=0, use_mmap=1, file_contents=none, encoding_override=none, formatting_info=false, on_demand=false, ragged_rows=false) data fmla_type_array = 4 fmla_type_cell = 1 fmla_type_cond_fmt = 8 fmla_type_data_val = 16 fmla_type_name = 32 fmla_type_shared = 2 mmap_available = 1 use_mmap = 1 xl_cell_blank = 6 xl_cell_boolean = 4 xl_cell_date = 3 xl_cell_empty = 0 xl_cell_error = 5 xl_cell_number = 2 xl_cell_text = 1 __version__ = '1.0.0' biff_text_from_num = {0: '(not biff)', 20: '2.0', 21: '2.1', 30: '3', ... empty_cell = empty:'' error_text_from_code = {0: '#null!', 7: '#p/0!', 15: '#value!', 23: ... obool = 3 oerr = 4 onum = 2 oref = -1 orel = -2 ostrg = 1 ounk = 0 okind_dict = {-2: 'orel', -1: 'oref', 0: 'ounk', 1: 'ostrg', 2: 'onum'... file c:\python34\lib\site-packages\xlrd\__init__.py
通过上述方法可以查看xlrd的帮助信息,里面有xlrd包中的一些模块以及一些成员变量、常量、函数。
二、python处理excel表格
1、打开excel表
import xlrd # 获取一个book对象 book = xlrd.open_workbook("1.xls") # 获取一个sheet对象的列表 sheets = book.sheets() # 遍历每一个sheet,输出这个sheet的名字(如果是新建的一个xls表,可能是sheet1、sheet2、sheet3) for sheet in sheets: print(sheet.name)
上面的帮助信息出现了这个函数:open_workbook() ,打开工作簿,这就打开了excel表。
返回的是一个book对象,通过book对象我们可以获得一个sheet的列表,上面的程序就简单地把每个sheet的名字都输了出来。
2、读出指定单元格内的数据
import xlrd # 获取一个book对象 book = xlrd.open_workbook("1.xls") # 获取一个sheet对象的列表 sheets = book.sheets() # 遍历每一个sheet,输出这个sheet的名字(如果是新建的一个xls表,可能是sheet1、sheet2、sheet3) for sheet in sheets: print(sheet.cell_value(0, 0))
读出单元格内数据函数 cell_value(row, col) ,行列均从0起。
除此之外,可以通过:
sheet.cell(row, col) # 获取单元格对象 sheet.cell_type(row, col) # 获取单元格类型
3、读取日期数据
如果excel存储的某一个单元格数据是日期的话,需要进行一下处理,转换为datetime类型
from datetime import datetime from xlrd import xldate_as_tuple # 获取一个book对象 book = xlrd.open_workbook("1.xls") # 获取一个sheet对象的列表 sheets = book.sheets() timeval = sheets[0].cell_value(0,0) timestamp = datetime(*xldate_as_tuple(timestamp, 0)) print(timestamp)
4、遍历每行的数据
rows = sheet.get_rows() for row in rows: print(row[0].value) # 输出此行第一列的数据
更多详解python中xlrd包的安装与处理excel表格。
其它类似信息

推荐信息