xlrd+xlwt+xlutils 处理excel的模块

介绍

安装:
	pip install xlrd xlwt xlutils
xlrd只能读取excel文件,
xlwt只能修改文件,
xlutils可以复制excel文件

xlrd

# xlrd只能读取excel文件

import xlrd
xlsfile = r"C:\Users\Administrator\Desktop\test\Account.xls"# 打开指定路径中的xls文件
book = xlrd.open_workbook(xlsfile)#得到Excel文件的book对象,实例化对象

# 获取sheet
sheet0 = r_file.sheets()[0]  # 通过sheet索引顺序获取
sheet1 = r_file.sheet_by_index(1) #通过索引顺序获取
sheet2 = r_file.sheet_by_name(u'Sheet1') #通过名称获取

# 获取行数、列数
nrows = sheet0.nrows #获取行数
ncols = sheet0.ncols #获取列数

# 读取某行、某列的内容
row = sheet0.row_values(0)  # 读取第一行
column = sheet0.col_values(0) #读取第一列

# 读取某个坐标的单元格内容   坐标(行,列)
cell_A1 = sheet0.cell(0,0).value
cell_A2 = sheet0.row(0)[0].value
cell_B1 = sheet0.cell(0,0).value


# 循环读取全部内容
nrows = sheet0.nrows #获取行数
res = []
for i in range(nrows):
    row = sheet0.row_values(i)
    res.append(row)
print(res)

xlwt

# xlwt只能修改文件

import xlwt

'''
encoding='utf-8'
style_compression:表示是否压缩,不常用。
cell_overwrite_ok=True  :可覆盖单元格,默认false
'''
book = xlwt.Workbook(encoding='utf-8', style_compression=0)  # 产生Workbook对象
sheet0 = file.add_sheet('test', cell_overwrite_ok=True)  # 产生表

# 添加数据
sheet0.write(0,0,'name')
sheet0.write(0,1,'age')
name = '马叉虫'
sheet0.write(1,0,name)
age = '18'
sheet0.write(1,1,age)


# 修改字体
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() #为样式创建字体
font.name = 'Times New Roman'
style.font = font #为样式设置字体
table.write(0, 1, 'some bold Times text', style) # 使用样式

# 保存
book.save(r'test.xls')

xlutils

# xlutils主要是拷贝的功能

from xlutils.copy import copy
file = xlrd.open_workbook(dir_path)  # 读取
cope_file = copy(file)  # 拷贝

sheet1=cope_file.get_sheet(1)  # 获取工作表
cope_file.save('cope_file.xls')  # 保存

小练习

import xlrd,xlwt,xlutils
from xlutils.copy import copy


file = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = file.add_sheet('people')


filed = ['name','age','sex']
people1 = ['jeff','18','男']

for index,vlaue in enumerate(filed):
    sheet.write(0,index,vlaue)
for index,vlaue in enumerate(people1):
    sheet.write(1, index, vlaue)
file.save(r'people.xls')
posted @ 2019-07-21 09:30  Jeff的技术栈  阅读(458)  评论(0编辑  收藏  举报
回顶部