python之操作excel

python操作excel主要是第三方模块xlrt,xlwt,xlutils,xlrt是读excel,xlwt是写excel,xlutils是修改excel。先安装这三个模块

一、读excel

import xlrd
book=xlrd.open_workbook('stu.xls')#打开一个excel文件
sheet=book.sheet_by_index(0)#根据下标获取工作表
sheet=book.sheet_by_name('sheet1')#根据名称获取工作表
print(sheet.nrows)#excel里面有多少行
print(sheet.ncols)#excel里面有多少列
print(sheet.cell(2,1).value)#获取指定单元格的值
print(sheet.row_values(3))#获取指定行的值,返回一个list
print(sheet.col_values(0))#获取指定列的值,返回一个list
for i in range(sheet.nrows):#循环获取每行的内容
    print(sheet.row_values(i))

#遍历sheet1中所有的单元格
for rown in range(sheet.nrows):
    for coln in range(sheet.ncols):
        cell=sheet.cell_value(rown,coln)
        print(cell)

二、写excel

import xlwt
book = xlwt.Workbook()#新建一个excel表
sheet = book.add_sheet('sheet1')#新建一个工作表,取名为sheet1
# sheet.write(0,0,'id')#指定行和列的位置写内容
# sheet.write(0,1,'username')#第1行第2列写入字段username
#二维数组
stus = [
    [1,'njf','1234'],
    [2,'xiaojun','1234'],
    [3,'hailong','1234'],
    [4,'xiaohei','1234'],
    [4,'xiaohei','1234'],
    [4,'xiaohei','1234'],
    [4,'xiaohei','1234'],
    [4,'xiaohei','1234'],
    [4,'xiaohei','1234'],
]
row = 0 #控制的是行
for stu in stus:#stu为二维数据里的元素,即stu为里面的一维数组
    col=0
    for s in stu:#stu为一维数组,s为一维数组中的元素
        sheet.write(row,col,s)#在指定行和列的位置写入元素
        col+=1
    row+=1
book.save('stu.xls')# 切记不要写.xlsx,将这个Excel保存

三、修改excel

import xlrd
from xlutils import copy
book = xlrd.open_workbook('stu.xls')#先用xlrd打开一个Excel
sheet=book.sheet_by_name('sheet1')#获取原excel表的sheet页
new_book = copy.copy(book)#然后用xlutils里面的copy功能,复制一个Excel
new_sheet = new_book.get_sheet(0)#获取复制后excel表的sheet页
print(sheet.nrows)
row=0
for i in range(sheet.nrows):#遍历9行,i为下标
    new_sheet.write(row,1,'刘怡涵')
    row+=1
new_book.save('stu.xls')#保存修改后的Excel文档

原文地址:https://www.cnblogs.com/balllyh/p/9880386.html