excel读取文件
基本操作
属性 | 描述 |
---|
sheet_names | 获取表的名字 |
sheet_by_index | 使用索引获取指定的对象 |
sheet_by_name | 使用名字 获取sheetd对象 |
shests | 获取所有的sheet对象 |
sheet.nrows | 这个sheet中的行数 |
sheet.ncols | 这个sheet中的列数 |
例如:
import xlrd_compdoc_commented
workbook = xlrd_compdoc_commented.open_workbook("成绩表.xlsx")
print(workbook.sheet_names())
sheet = workbook.sheet_by_index(1)
print(sheet.name)
sheet = workbook.sheet_by_name("2班")
print(sheet.name)
sheets = workbook.sheets()
for sheet in sheets:
print(sheet.name)
有关于cell 表格中的一个格子
属性 | 描述 |
---|
cell(row,col) | 获取指定的行和列 |
row_slice(row,start_col,end_col) | 获取指定行的某几列 |
col_slice(col,start_row,end_col) | 获取指定列的某几行 |
cell_value(row,col) | 获取指定行和列的值 |
row_values(row,start_col,end_col) | 获取指定行的某几列 |
col_values(col,start_row,end_row) | 获取指定列的某几行 |
代码
import xlrd_compdoc_commented
workbook = xlrd_compdoc_commented.open_workbook("成绩表.xlsx")
from xlrd.sheet import Cell
sheet = workbook.sheet_by_index(0)
cell = sheet.cell(1,1)
cells = sheet.row_slice(1,0,4)
for cell in cells:
print(cell.value)
cells = sheet.col_slice(0,1,sheet.nrows)
for cell in cells:
print(cell.value)
cell数据类型
属性 | 类型 |
---|
XL_CELL_TEXT | 文本类型 |
XL_CELL_NUMBER | 数值类型 |
XL_CELL_DATE | 日期时间类型 |
XL_CELL_BOOLEAN | 布尔类型 |
XL_CELL_EMPTY | 空白数据类型 |
excel的写入
import xlwt
import random
workbook=xlwt.Workbook()
sheet=workbook.add_sheet("sheet1")
headers=['姓名','年龄','成绩']
for index,header in enumerate(headers):
sheet.write(0,index,header)
names=['张三','李四','王五']
for index,name in enumerate(names):
sheet.write(index+1,0,name)
for row in range(1,4):
for col in range(1,4):
sheet.write(row,col,random.randint(70,100))
workbook.save("xinxi.xls")
excel 文件的编辑
import xlrd_compdoc_commented
import xlwt
rwd=xlrd_compdoc_commented.open_workbook("成绩表.xlsx")
rsheet=rwd.sheet_by_index(0)
rsheet.put_cell(0,4,xlrd_compdoc_commented.XL_CELL_TEXT,"总分",None)
for row in range(1,rsheet.nrows):
grades=rsheet.row_values(row,1,4)
total=sum(grades)
rsheet.put_cell(row,4,xlrd_compdoc_commented.XL_CELL_TEXT,total,None)
rsheet.put_cell(0,5,xlrd_compdoc_commented.XL_CELL_TEXT,"平均分",None)
for row in range(1,rsheet.nrows):
grades=rsheet.row_values(row,1,4)
avge=sum(grades)/3
print(avge)
rsheet.put_cell(row,5,xlrd_compdoc_commented.XL_CELL_TEXT,avge,None)
wwb=xlwt.Workbook()
wsheet=wwb.add_sheet("sheet1")
nrows=rsheet.nrows
ncols=rsheet.ncols
for row in range(0,nrows):
for col in range(0,ncols):
wsheet.write(row,col,rsheet.cell_value(row,col))
wwb.save("abc.xls")
excel文件的写入
excel 文件写入
wwb=xlwt.Workbook()
wsheet=wwb.add_sheet("sheet1")
nrows=rsheet.nrows
ncols=rsheet.ncols
for row in range(0,nrows):
for col in range(0,ncols):
wsheet.write(row,col,rsheet.cell_value(row,col))
wwb.save("abc.xls")