首页 > 代码库 > python操作excel
python操作excel
import xlrd, xlwt, xlutils
############ 读excel ###############
book = xlrd.open_workbook(‘C:\\Users\lingyul\Desktop\students.xlsx‘)#打开excel
print(book.sheet_names())#获取所有sheet页的名字
sheet1 = book.sheet_by_index(0)##根据sheet页的下标获取sheet页
sheet2 = book.sheet_by_name(‘students‘)#根据sheet页的名字获取sheet页
print(sheet1,sheet2)
print(‘row_all‘,sheet1.nrows)#获取所有行数
print(‘ncols_all‘,sheet1.ncols)#获取所有列数
print(sheet1.row_values(0))#根据行号打印某一行
sheet1.row_values(0)[0]#第0行的第0个元素
print(sheet1.col_values(0))#根据列号打印某一列
sheet1.col_values(0)[0]#第0列的第0个元素
print(‘####‘,sheet1.cell(2,2).value)#不加value的运行结果为:text:‘小明‘。打印第二行第二列的数据,即获取单元格数据
lis=[]
sheet1 = book.sheet_by_index(0)
ncols_all = sheet1.ncols
for row in range(1,sheet1.nrows):
students = {}
id = sheet1.cell(row, 0).value
name = sheet1.cell(row, 1).value
sex = sheet1.cell(row, 2).value
students[‘id‘]=id
students[‘name‘]=name
students[‘sex‘]=sex
lis.append(students)
print(lis)
############ 写excel ###############
import xlwt
book = xlwt.Workbook()#新建一个excel对象
sheet = book.add_sheet(‘stu‘)# 新建一个sheet
# sheet.write(0,0,‘编号‘)
# book.save(‘stu.xls‘)
## 写 excel,时候,保存的文件必须以xls结尾
title = [‘编号‘, ‘姓名‘, ‘性别‘]
stus = [[‘mary‘,20,‘女‘,89.9],[‘mary‘,20,‘女‘,89.9],[‘mary‘,20,‘女‘,89.9],[‘mary‘,20,‘女‘,89.9]]
for i in range(len(title)):
sheet.write(0,i,title[i])
for row in range(len(lis)):
new_row=row+1
id = lis[row][‘id‘]
name = lis[row][‘name‘]
sex = lis[row][‘sex‘]
sheet.write(new_row,0,id)
sheet.write(new_row, 1, name)
sheet.write(new_row, 2, sex)
book.save(‘stu.xls‘)
import xlrd
from xlutils.copy import copy
def copy():
book = xlrd.open_workbook(‘new_stu.xls‘)
new_book = copy(book)#通过xlutils里面的copy复制一个excel对象
sheet = new_book.get_sheet(0)#获取sheet页
sheet.write(0,0,‘id‘)
new_book.save(‘new_stu_1.xls‘)
json_list= {
"1":["小花",99,100,98.5],
"2":["小王",90,30.5,95],
"3":["小明",67.5,49.6,88]
}
title = [‘学号‘,‘姓名‘,‘语文成绩‘,‘数学成绩‘,‘英语成绩‘,‘总分‘,‘平均分‘]
book = xlrd.open_workbook(‘new_stu.xls‘)
new_book = copy(book) # 通过xlutils里面的copy复制一个excel对象
sheet = new_book.get_sheet(0) # 获取sheet页
sheet.write(0, 0, ‘id‘)
new_book.save(‘new_stu_1.xls‘)
python操作excel
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。