python转化成excel_python转换excel成py文件
python轉換excel成py文件
文件結構如下:
originExcelFolder放用來轉換的excel文件。
targetPyFolder用來存放最后生產的py文件。
setting.py用來配置excel表到py的對應關系。
excel2py.py是主要的處理文件。
Excel文件,A注意表名字,B注意sheet名字。
代碼如下:
setting.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# setting.py # 定義生成py表的格式
Dict ={
"student":{
"id": {'type':int, 'default': 0},
"name":{'type':str, 'default': None},
"age":{'type':int, 'default': 0},
"sex":{'type':str, 'default': 'F'},
}
}
excel2.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
# transfer excel to py
# 處理excel表格生成對應的py文件
from openpyxl import Workbook
from openpyxl import load_workbook
import sys
import os
import time
from setting import Dict as tranDict
TARGET_PY_PATH = "targetPyFolder/"
ORIGIN_EXCEL_PATH = "./originExcelFolder/"
LOG_LEVEL_INFO = "INFO"
LOG_LEVEL_DEBUG = "DEBUG"
LOG_LEVEL_ERR = "ERROR"
class Excel2py:
def __init__(self):
self.init()
def init(self):
self.tempSheetName = None
self.tempFileName = None
self.target_dict = {}
def handleFiles(self):
# 切換到handleExcel所在的那個路徑
os.chdir(sys.path[0])
# 加載已經存在的excel,(這時候excel與.py文件在同一級目錄下)
self.tempFileName = ORIGIN_EXCEL_PATH + "test.xlsx"
wb = load_workbook(self.tempFileName)
# 所有的頁的名字
sheetNames = wb.sheetnames
# 這里只取出了第一個頁來處理,
self.tempSheetName = str(sheetNames[0])
ws = wb[self.tempSheetName]
# 表的關鍵字
key_dict = {}
# 目標字典
self.target_dict = {}
# 取出關鍵字
for column_index in range(2,ws.max_column+1):
val = ws.cell(row=2, column=column_index).value
val = str(val)
if val:
key_dict[column_index] = val
# 遍歷表的每行
for row_index in range(3, ws.max_row+1):
temp_dict = {}
for index in key_dict:
val = ws.cell(row=row_index,column=index).value
# 類型處理
val = self.handleType(self.tempSheetName,key_dict[index],val)
item_id = int(ws.cell(row=row_index,column=1).value)
temp_dict[key_dict[index]] = val
self.target_dict[item_id] = temp_dict
self.writeToPy()
def handleType(self,sheetName,stype,value):
"""
數據類型處理
"""
typeDict = tranDict[sheetName].get(stype)
rtnValue = typeDict['default']
if value is None or value == "None":
rtnValue = typeDict['default']
elif not isinstance(value, typeDict['type']):
rtnValue = (typeDict['type'])(value)
# 異常處理--Todo
# 寫處理日志-Todo
else:
rtnValue = value
return rtnValue
def writeToPy(self,):
"""
寫成py文件
"""
fileName = TARGET_PY_PATH + self.tempSheetName + ".py"
if os.path.exists(fileName):
os.remove(fileName)
pyFile = open(fileName,'a')
ids = self.target_dict.keys()
ids.sort()
pyFile.write("\nDict = {\n\n")
for id in ids:
pyFile.write(str(id)+":"+str(self.target_dict[id]))
pyFile.write(",\n")
pyFile.write("\n}\n")
#pyFile.flush()
pyFile.close()
logInfo = '=========transfer sheet:' + self.tempSheetName + " success"
print '=========logInfo:', logInfo
self.tranlog(self.tempFileName, self.tempSheetName,LOG_LEVEL_INFO, logInfo)
def tranlog(self, excelName, sheetName, logLevel, logInfo):
"""
寫轉換日志
"""
logFile = "log.log"
pyFile = open(logFile,'a')
logMsg = '\n'+logLevel+"__"+str(time.time())+"__"+excelName.split('/')[-1]+"_"+sheetName+": "+logInfo
pyFile.write(logMsg)
# pyFile.flush()
pyFile.close()
if __name__ == "__main__":
Excel2pyObj = Excel2py()
Excel2pyObj.handleFiles()
注意:這里只處理了一個表的一個sheet,如果想要處理多個表多個sheet可稍作修改即可。
總結
以上是生活随笔為你收集整理的python转化成excel_python转换excel成py文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中的pandas怎么安装_如
- 下一篇: python编写函数求斐波那契数列的某一