目录
openpyxl支持.xlsx格式,所有我选择了这个
一、场景
场景:需要将全部excel数据读取出来
二、实现思想
实现思想:封装起来,通过传参excel文件名以及对应的sheet名称即可 return字典或者元组方式的两种类型数据,具体根据需要去调用
三、代码:
# -*- coding: utf-8 -*-
# @Time : 2021/6/1 17:34
# @Project : monthreport
# @Author : testing
# @File : do_excel.py
# @Software: PyCharm
from openpyxl import load_workbook
import os
import sys
import datetime
from common import get_path
from common.read_logs import MyLogger
from common.read_config import ReadConfig
# 根目录
path = os.path.dirname(get_path.get_path())
# 进入到数据目录
Base_Path = os.path.join(path, 'data')
print(Base_Path)
class ReadExcel(object):
def __init__(self, file_path, sheet_name, num):
self.log = MyLogger().get_log()
# 拼成完整文件名
file_path = file_path +'.xlsx'
self.file_path = os.path.join(Base_Path, file_path)
print(self.file_path)
self.sheet_name = sheet_name
if not os.path.exists(self.file_path):
self.log.error(self.file_path + "\t 该文件不存在,请确认文件路径!")
sys.exit(1)
try:
self.workbook = load_workbook(self.file_path)
except Exception as e:
self.log.error("打开文件发生错误:%s" % e)
# 获取读文件中所有的sheet
self.worksheet = self.workbook.get_sheet_names()
# 获取第一个sheet内容(这里参数了)
self.ws = self.workbook.get_sheet_by_name(self.worksheet[num])
# 表头
self.title = list(self.ws.rows)[0]
# 获取sheet的最大行数和列数
self.rows = self.ws.max_row
self.cols = self.ws.max_column
if self.rows == 0 or self.cols == 0:
self.log.error("表格为空,请确认测试数据是否正常写入!")
# 有错误退出
sys.exit(1)
def readExcel_to_dict(self):
s_data = []
for i in range(2, self.rows+1):
sheet_data = {}
for j in range(1, self.cols+1):
c_data = self.ws.cell(i, j).value
# 这里-1 目的 因为excel是从1开始,python列表需要从0开始取值
sheet_data[self.title[j-1].value] = c_data
s_data.append(sheet_data)
return s_data
def readExcel_to_tuple(self):
s_data = []
for i in range(2, self.rows+1):
sheet_data = []
for j in range(1, self.cols+1):
c_data = self.ws.cell(i, j).value
# if isinstance(c_data, datetime.datetime):
# # if type(c_data) == datetime.datetime:
# c_data = c_data.strftime('%Y/%d/%m %H:%M:%S')
sheet_data.append(c_data)
s_data.append(tuple(sheet_data))
return s_data
if __name__ == '__main__':
name = '2021测试工作内容'
# d = ReadExcel(name, "2021工作内容分配", 0).readExcel_to_dict()
d = ReadExcel(name, "2021工作内容分配", 0).readExcel_to_tuple()
print(d)
print(type(d))
将获取的数据进行应用 --这里使用了pyecharts