Python读取Excel表格数据
方法一-一次性读取所有Excel表格数据```pythonfrom openpyxl import load_workbookclass DoExcel :def __init__(self,filename,sheet_name):self.filename=filenameself.sheet_name=sheet_namedef get_data(self):wb=load_workbook
·
**方法一:**一次性读取所有Excel表格数据
```python
from openpyxl import load_workbook
class DoExcel :
def __init__(self,filename,sheet_name):
self.filename=filename
self.sheet_name=sheet_name
def get_data(self):
wb=load_workbook(self.filename)
sheet=wb[self.sheet_name]
test_data=[]
for i in range(1,sheet.max_row+1):
sub_data={}
sub_data['method']=sheet.cell(i,1).value
sub_data['url']=sheet.cell(i,2).value
sub_data['data']=sheet.cell(i,3).value
sub_data['except']=sheet.cell(i,4).value
test_data.append(sub_data)
return test_data
if __name__ == '__main__':
res= DoExcel('../class_01/test.xlsx','tet').get_data()
print(res)
**方法二:**读取所需的单元格数据
from openpyxl import load_workbook
class DoExcel:
def __init__(self,file_name,sheet_name):
self.file_name=file_name
self.sheet_name=sheet_name
#获取表单对象
self.sheet_obj=load_workbook(self.file_name)[self.sheet_name]
#定义读取不同表格数据方法
def get_data(self,i,j):
return self.sheet_obj.cell(i,j).value
if __name__ == '__main__':
res=DoExcel('../class_01/test.xlsx','tet').get_data(1,1)
print(res)
**方法三:**excel头部添加标题行
from openpyxl import load_workbook
class DoExcel:
def __init__(self, file_name, sheet_name):
self.file_name = file_name
self.sheet_name = sheet_name
def get_header(self):
#获取第一行标题行
header=[]
wb = load_workbook(self.file_name)
sheet = wb[self.sheet_name]
for i in range(1,sheet.max_column+1):
header.append(sheet.cell(1,i).value)
return header
def get_data(self):
wb=load_workbook(self.file_name)
sheet=wb[self.sheet_name]
#获取第一行的头部信息
header=self.get_header()
test_data=[]
for i in range(2,sheet.max_row+1):
sub_data={}
for j in range(1,sheet.max_column+1):
sub_data[header[j-1]]=sheet.cell(i,j).value
test_data.append(sub_data)
return test_data
if __name__ == '__main__':
res = DoExcel('../class_01/test.xlsx', 'tet').get_data()
print(res)
更多推荐
已为社区贡献1条内容
所有评论(0)