表格格式
方法一:使用xlrd
import xlrd
1.读取Excel文件
workbook = xlrd.open_workbook('plc.xlsx')
2.读取第一个表
sheet = workbook.sheet_by_index(0)
3.获取表格总行数
total_rows = sheet.nrows
4.创建列表,存储表格一行中每一列信息
plc_info = []
for row in range(1, total_rows): # 获取第1到最后行的数据id = int(sheet.cell_value(row,0)) #获取第一行索引为0的数据plc_name = sheet.cell_value(row, 1) # 获取PLC名plc_ip = sheet.cell_value(row, 2) # 获取IP地址db_number = int(sheet.cell_value(row, 3)) # 获取DB块号start_address = int(sheet.cell_value(row,4)) #获取起始地址db_size = int(sheet.cell_value(row, 5)) # 获取DB大小data_type = sheet.cell_value(row, 6) # 获取数据类型
5.将每一行的数据插入到列表中
plc_info.append({'id':id,'name': plc_name, 'ip': plc_ip, 'db': db_number,'address': start_address,'db_size': db_size, 'data_type': data_type})
6.打印total_rows,plc_info
源码
import xlrd# 读取Excel文件
workbook = xlrd.open_workbook('plc.xlsx')
# 读取第一个表
sheet = workbook.sheet_by_index(0)
# 获取表格总行数
total_rows = sheet.nrows
print(total_rows)
# 获取表的PLC信息
plc_list = []
for row in range(1, total_rows): # 获取第1到最后行的数据id = int(sheet.cell_value(row,0)) #获取第一行索引为0的数据plc_name = sheet.cell_value(row, 1) # 获取PLC名plc_ip = sheet.cell_value(row, 2) # 获取IP地址db_number = int(sheet.cell_value(row, 3)) # 获取DB块号start_address = int(sheet.cell_value(row,4)) #获取起始地址db_size = int(sheet.cell_value(row, 5)) # 获取DB大小data_type = sheet.cell_value(row, 6) # 获取数据类型plc_list.append({'id':id,'name': plc_name, 'ip': plc_ip, 'db': db_number, 'address': start_address,'db_size': db_size, 'data_type': data_type})
print(plc_list)
方法二:使用pandas
import pandas as pd
1.读取excel表数据
data = pd.read_excel('./plc.xlsx', sheet_name='plc')
2.创建列表,遍历表格数据存储到字典
plc_list = []
for _, row in data.iterrows():plc_dict = {'id': row['id'],'plc_name':row['plc_name'],'plc_ip': row['plc_ip'],'db_number': row['db_number'],'start_address': row['start_address'],'db_size':row['db_size'],'data_type':row['data_type']}
3.将字典数据添加到列表中
plc_list.append(plc_dict)
4.打印plc_list
源码
import pandas as pd# 读取excel表数据存储以字典存储到列表
data = pd.read_excel('./plc.xlsx', sheet_name='plc')
plc_list = []
for _, row in data.iterrows():plc_dict = {'id': row['id'],'plc_name':row['plc_name'],'plc_ip': row['plc_ip'],'db_number': row['db_number'],'start_address': row['start_address'],'db_size':row['db_size'],'data_type':row['data_type']}plc_list.append(plc_dict)
print(plc_list)