Python操作Excle

python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。可从这里下载https://pypi.python.org/pypi。下面分别记录python读和写excel.

一、Python读Excel-----xlrd

Python操作Excle

python 对 excel基本的操作如下:

'''
xlrd
'''
import xlrd
from xlrd.book import Book def read_excel():
# 1. 打开excel
workbook = xlrd.open_workbook(r"D:\web\test.xlsx")
# <xlrd.book.Book object at 0x000001F68F4C7CC0> <class 'xlrd.book.Book'>
print(workbook,type(workbook)) # 2. 获取所有的sheet
print(workbook.sheet_names()) # ['Sheet1']
sheet1 = workbook.sheet_names()[0] # 3. 根据sheet索引或者名称获取sheet内容
sheet1 = workbook.sheet_by_index(0).name
print(sheet1)
sheet1 = workbook.sheet_by_name('Sheet1')
print(sheet1)
sheet1 = workbook.sheet_by_name('Sheet1')
# 4. sheet的名称,行数,列数
"""
name age
张三 10
李四 10
王五 10
""" print(sheet1.name) # Sheet1
print(sheet1.nrows) # 4行
print(sheet1.ncols) # 2列 # 5. 获取整行和整列的值(数组)
rows = sheet1.row_values(1) # 从0开始,获取第一行的内容
cols = sheet1.col_values(1) # 从0开始,获取第一列的内容 print(rows)
print(cols) # 6. 获取单元格内容 zs = sheet1.cell(1,0)
print(zs) # text:'张三' ls = sheet1.cell_value(2,0)
print(ls) # 李四 print(sheet1.row(1)[0]) # text:'张三' # 7. 获取单元格内容的数据类型
print(sheet1.cell(2,0).ctype) # read_excel()
上一篇:c++异常安全和copy and swap策略


下一篇:Cognition math based on Factor Space (2016.05)