Jquery中文网 www.jquerycn.cn
Jquery中文网 >  Python编程  >  Python入门  >  正文 python怎么连接excel

python怎么连接excel

发布时间:2021-04-09   编辑:www.jquerycn.cn
jquery中文网为您提供python怎么连接excel等资源,欢迎您收藏本站,我们将为您提供最新的python怎么连接excel资源

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

xlwt缺点,无法复制Excel格式

xlutils 可以复制Excel格式

一、安装第三方库

pip install xlrd

pip  install xlwt

pip install xlutils

相关推荐:《Python视频教程》

二、第三方库的使用

1、xlrd读Excel

import 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写Excel

import 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

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
在C#.net 中读取EXCEL文件的数据
python怎么读取和写入excel表格
python怎么读取excel中的数值
python怎么关闭指定的excel
python怎么读取excel表格
python怎么读写excel文件
python的xlwings模块怎么用于excel?
python怎么存储数据
数据分析师为什么要学python

[关闭]