网络编程
位置:首页>> 网络编程>> Python编程>> python3:excel操作之读取数据并返回字典 + 写入的案例

python3:excel操作之读取数据并返回字典 + 写入的案例

作者:放开那只大熊猫  发布时间:2023-11-25 17:59:22 

标签:python3,excel,读取,字典,写入

excel写入数据,使用openpyxl库


class WriteExcel:
def __init__(self,path):
 self.path = path

def write_excel(self, sheet_name, content):
 """
 在excel指定sheet中的写入指定内容,以追加方式
 :return:
 """
 wb = openpyxl.load_workbook(self.path)
 ws = wb[sheet_name]
 # 获取最大行
 row_num = ws.max_row
 try:
  ws.cell(row=row_num+1, column=1).value = content
 except Exception as msg:
  print('写入excel失败:', msg)
 finally:
  wb.save(self.path)

if __name__ == '__main__':
WE = WriteExcel('../config/data.xlsx')
WE.write_excel(sheet_name='user', content='瑟瑟发抖')

python3:excel操作之读取数据并返回字典 + 写入的案例

excel读取数据,使用xlrd库


class ReadExcel:
def __init__(self,path):
 self.path = path

def read_excel(self,row):
 """
 遍历excel所有sheet,并以字典返回
 :param row:
 :return:
 """
 with xlrd.open_workbook(self.path, 'rb') as book:
  sheets = book.sheet_names() # 找到所有sheets
  data_dict = {}
  for sheet in sheets:
   table = book.sheet_by_name(sheet) # 找到要操作的sheet

# 获取sheet所有列数
   col_num = table.ncols
   # 读取第一行的值,作为每个sheet返回字典的key
   keys = table.row_values(0)

# 读取除指定行,作为每个sheet返回字典的value
   values = table.row_values(row)

# 遍历所有列,并以字典接收,其中第一行作为字典的key,其他行作为字典的value
   sheet_dict = {}
   for col in range(col_num):
    sheet_dict[keys[col]] = values[col]

# 遍历所有sheet,并以字典接收返回,其中sheet名称作为字典的key,每个sheet的数据作为字典的value
   data_dict[sheet] = sheet_dict
 return data_dict

python3:excel操作之读取数据并返回字典 + 写入的案例

读取结果:

python3:excel操作之读取数据并返回字典 + 写入的案例

补充知识:Python+selenium+ddt数据驱动测试

我就废话不多说了,大家还是直接看代码吧~


import ddt

testData = ['1','2','3']
print testData

@ddt.ddt
class Bolg(unittest.TestCase):

def setUp(self):
   print('setUp')

@ddt.data(*testData)
 def test_l(self, data):
   print(data)

def tearDown(self):
   print('tearDown')

if __name__ == "__main__":
 unittest.main()

============
1
2
3

来源:https://blog.csdn.net/yijinaqingan/article/details/105794433

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com