python操作excel,python操作excel使用xlrd、xlwt和xlutils模块,xlrd模块是读取excel的,xlwt模块是写excel的,xlutils是用来修改excel的。这几个模块使用pip安装即可,下面是这几个模块的使用。
import xlrd,xlwt,xlutils
#写excel
book = xlwt.Workbook() #创建一个excel对象
sheet = book.add_sheet('sheet1') #添加一个sheet页面
sheet.write(0,0,'姓名') #第0行第0列最后一个代表单元格的值
sheet.write(0,1,'年龄') #第0行第一列
sheet.write(0,2,'身高') #第0行第二列
sheet.write(1,0,'郝帅')
sheet.write(1,1,'38') sheet.write(1,2,'150cm')
titile = ['姓名','班级','住址','手机号']
data = [
['红孩儿','观音寺','南海','110'],
['银角大王','天庭','老君炉','120'],
['黄袍怪','鬼道班','某山上','119']
]
####控制tile
i=0 控制列
for j in title:
sheet.write(0,i,j)
i+=1
####控制内容
line = 1 #控制写的行,从第二行开始写
for d in data:
row = 0
for dd in d:
sheet.write(line,row,dd)
row+=1
line+=1
book.save('hh.xls') #写文件保存的是偶必须是xls格式,要不然打不开
上面的代码可以用下面的代替
for d in range(len(data)) for dd in range(len(data[d])): sheet.write(d+1,dd,data[d][dd])
#读excel
import xlrd
book = xlrd.open_workbook('ggg.xls') #1、先新建一个excel对象
sheet = book.sheet_by_index(0) #2、根据下标获取sheet页
#sheet = book.sheet_by_name() #根据名字获取sheet页面
row= sheet.nrows #获取sheet页的总行数
print(sheet.ncols) #获取sheet页的总列数
print(sheet.cell(1,1)value) #通过行和列获取单个单元格的值 返回str
for i in range(row)
print(sheet.row_values(i)) #获取行里所有的值 返回list
'''
示例:将没交作业和交作业的excel里的内容保存到mysql里 insert into jxz_stu (name,cl,c2,c3) values
'''
insert into jxz_stu (name,cl,c2,c3) values ('牛寒阳','交','交','交');
'''
import pymysql,xlwt
def op_mysql(sql):
try :
conn = pymysql.connect(host='211.149.218.16',user='jxz',passwd='123456',port=3306,db='jxz',charset='utf8')
cur = conn.cursor()
except Exception as e :
raise e
else:
try:
cur.execute(sql)
except Exception as e:
raise e
else:
if sql.startswith('select'):
res =cur.fetchall()
else:
conn.commit()
res =88
return res
finally:
cur.close()
conn.close()
def is_up(a):
if a:
return '交了'
else:
return '没交'
def copy_excel(filename):
import xlrd
book = xlrd.open_workbook(filename)
sheet = book.sheet_by_index(0)
rows = sheet.nrows
i = 1
for i in range(rows):
res =sheet.row_values(i)
c1 = is_up(res[1])
c2 = is_up(res[2])
c3 = is_up(res[3])
sql ="insert into jxz_stu (name,cl,c2,c3) values ('%s','%s','%s','%s')"%(res[0],c1,c2,c3)
op_mysql(sql)
copy_excel('stu.xlsx')
#####修改excel
'''
修改excel
1、打开一个文件
2、copy一下
3、修改文件
4、删除之前的文件,并且重命名新的文件
'''
from xlrd import open_workbook
from xlutils.copy import copy
import os
book = open_workbook('ggg.xls')
new_book = copy(book)# #通过xlutils里面的copy复制一一个excel对象
sheet = new_book.get_sheet(0) # # 通过下标获取到新的excel里面的sheet页
sheet.write(1,1,'fsfads')
new_book.save('jjj.xls')
os.remove('ggg.xls')
os.rename('jj.xls','ggg.xls')