当前位置:首页 » 数据分析 » 正文

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

看: 1052次  时间:2020-10-09  分类 : 数据分析

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='瑟瑟发抖')

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

读取结果:

补充知识: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

以上这篇python3:excel操作之读取数据并返回字典 + 写入的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:selenium  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!