python读取Excel实例详解

yipeiwu_com6年前Python基础

本文实例为大家分享了python读取Excel实例的具体代码,供大家参考,具体内容如下

1.操作步骤:

(1)安装python官方Excel库-->xlrd

(2)获取Excel文件位置并读取

(3)读取sheet

(4)读取指定rows和cols内容

2.示例代码:

# -*- coding: utf-8 -*-
 
import xlrd 
from datetime import date,datetime
 
def read_excel():
 
#文件位置
ExcelFile=xlrd.open_workbook(r'C:\Users\Administrator\Desktop\TestData.xlsx') 
#获取目标EXCEL文件sheet名 
print ExcelFile.sheet_names()
 
#------------------------------------ 
#若有多个sheet,则需要指定读取目标sheet例如读取sheet2 
#sheet2_name=ExcelFile.sheet_names()[1] 
#------------------------------------ 
#获取sheet内容【1.根据sheet索引2.根据sheet名称】
#sheet=ExcelFile.sheet_by_index(1)
sheet=ExcelFile.sheet_by_name('TestCase002')
#打印sheet的名称,行数,列数
print sheet.name,sheet.nrows,sheet.ncols 
#获取整行或者整列的值
rows=sheet.row_values(2)#第三行内容
cols=sheet.col_values(1)#第二列内容
print cols,rows 
#获取单元格内容
print sheet.cell(1,0).value.encode('utf-8') 
print sheet.cell_value(1,0).encode('utf-8') 
print sheet.row(1)[0].value.encode('utf-8') 
#打印单元格内容格式
 
print sheet.cell(1,0).ctype
 
if__name__ =='__main__':
 
read_excel()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Puppeteer使用示例详解

Puppeteer使用示例详解

PhantomJS曾经是无头浏览器里的王者,测试、爬虫等都在使用,随着GoogleChrome Headless的出现,PhantomJS的作者已经明确表示不在更新,而GoogleChr...

Python中SOAP项目的介绍及其在web开发中的应用

SOAP.py 客户机和服务器 SOAP.py 包含的是一些基本的东西。没有 Web 服务描述语言(Web Services Description Language,WSDL)或者任何...

Linux(Redhat)安装python3.6虚拟环境(推荐)

python是3.6 centos 6 64位 1.安装python 2.安装pip wget https://bootstrap.pypa.io/get-pip.py --no-c...

python函数修饰符@的使用方法解析

python函数修饰符@的作用是为现有函数增加额外的功能,常用于插入日志、性能测试、事务处理等等。 创建函数修饰符的规则: (1)修饰符是一个函数 (2)修饰符取被修饰函数为参数...

在python中利用KNN实现对iris进行分类的方法

如下所示: from sklearn.datasets import load_iris iris = load_iris() print iris.data.shape...