python怎么连接excel_python连接excel的方法

python连接excel的方法

发布时间:2020-09-01 10:28:47

来源:亿速云

阅读:62

作者:小新

小编给大家分享一下python连接excel的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。

xlwt缺点,无法复制Excel格式

xlutils 可以复制Excel格式

一、安装第三方库

pip install xlrd

pip  install xlwt

pip install xlutils

二、第三方库的使用

1、xlrd读Excelimport xlrd

book=xlrd.open_workbook("demo2.xls")

sheet1=book.sheet_by_index(0) #通过索引取TAB,且返回的是对象

#sheet1=book.sheet_by_name('sheet1')#通过名字取TAB,且返回的是对象

print(sheet1.row_values(1)) #取某一行的数据

print(sheet1.col_values(0)) #取某一列的数据

print(sheet1.cell_value(0,0)) #取某一单元格内容

print(sheet1.cell(0,0).value) #取某一单元格内容

print(sheet1.col_values(1,0,6)) #取从第一列的第0行到第6行的数据,不包含第6行

print(sheet1.name) #取TAB名称

print(sheet1.nrows) #取共多少行

print(sheet1.ncols) #取共多少列

print(sheet1.number) #取TAB的index

print(sheet1.row_len(0)) #每行的长度

2、xlwt写Excelimport xlwt

book=xlwt.Workbook() #声明对象

sheet=book.add_sheet('标签1') #添加TAB签

list=["姓名","年龄","性别","班级"] #表头数据

x,y=0,0

for i in list:

sheet.write(x,y,i)  #遍历写表头

y+=1

book.save("b.xls")

#保存的时候,如果你用的是微软的Office,后缀就用.xls

#如果是wps .xls,.xlsx

python怎么连接excel_python连接excel的方法_第1张图片

3、xlutils复制修改

修改的思路是:打开----复制----修改import xlrd

from xlutils import copy

book=xlrd.open_workbook("book.xls") #打开文件

newbook=copy.copy(book) #复制文件

sheet=newbook.get_sheet(0) #获取表TAB

list=["姓名","年龄","性别","班级"]

for col,t in enumerate(list): #枚举方式遍历写表头

sheet.write(0,col,t)

newbook.save("book.xls")

python怎么连接excel_python连接excel的方法_第2张图片

看完了这篇文章,相信你对python连接excel的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

你可能感兴趣的:(python怎么连接excel)