日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python转化成excel_python转换excel成py文件

發布時間:2024/9/15 python 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。