xlrd模块
1、xlrd模块介绍
读取Excel表格数据;
支付xlsx和xls格式的表格数据
安装方式:pip install xrld
导入模块:import xlrd
2、操作方法:
读取Excel表格 xlrd.open_workbook(filename) 参数filename需要打开的表格路径文件
获取sheet内容,索引从sheetx开始 execl.sheet_by_index(self,sheet) 参数sheet表示从参数开始
获取表格行数 nrows
获取表格列数 ncols
获取表格每行内容 get_rows()
获取表格每列内容 get_cols()
获取单元格数据内容 get_rows(row,cols).value
import xlrd
import time
class ReadExcle(object):
def __init__(self,file_name=None,index=None):
if file_name==None:
self.file_name=r'F:\项目\京东登陆\Testcfg\测试数据.xls'
else:
self.file_name = file_name
if index==None:
index=0
# 打开Excel表格
self.excel = xlrd.open_workbook(self.file_name)
# 获取sheet内容,索引从self.index开始
self.data = self.excel.sheet_by_index(index)
'''
获取Excel表格行数
'''
def get_rows(self):
rows = self.data.nrows
if rows >=1:
return rows
return None
'''
获取Excel表格列数
'''
def get_cols(self):
cols = self.data.ncols
if cols >=1:
return cols
return None
'''
获取Excel每行的内容
'''
def get_rows_content(self):
excle_row=[]
if self.get_rows()>=1:
#for循环获取表格内所有有效行数的内容
for i in range(1,self.get_rows()):
#获取行数内容
row = self.data.row_values(i)
excle_row.append(row)
return excle_row
return None
'''
获取Excel每列的内容
'''
def get_cols_content(self):
excel_cols=[]
if self.get_cols()>=1:
for i in range(self.get_cols()):
cols = self.data.col_values(i)
excel_cols.append(cols)
return excel_cols
return None
'''
获取单元格数据
'''
def get_cell_content(self,row,clos):
if self.get_rows()>=1 and self.get_cols()>=1:
cell = self.data.cell(row,clos).value
return cell
return None
xlutils模块
1、xlutils模块操作
第三方安装方式:pip install xlutils
导入模块 from xlutils.copy import copy
拷贝表格 copy(excel)
写入数据到表格单元格中 get_sheet(0).write(row,clos,value) 参数row:行;clos:列;单元格:value
保存文件 save(filename) 参数filename表示为表格
import xlrd
from xlutils.copy import copy
'''
写入数据
'''
def write_data(self,row,clos,value):
read_value = xlrd.open_workbook(self.file_name)
# c拷贝Excel文件
read_data = copy(read_value)
# 写入数据
read_data.get_sheet(0).write(row,clos,value)
# 保存文件
read_data.save(self.file_name)
time.sleep(1)
来源:https://www.cnblogs.com/zihkj/p/12163730.html