2021-03-20
程序员文章站
2022-07-13 16:54:51
...
from openpyxl import Workbook
import os
import uuid
import socket
XML_DIRS = "/var/user_xml/"
if not os.path.exists(XML_DIRS):
os.mkdir(XML_DIRS)
def get_ip():
# 获取本机计算机名称
hostname = socket.gethostname()
# 获取本机ip
ip = socket.gethostbyname(hostname)
return ip
order_list = ["姓名", "地址", "出生日期", "性别", "电话", "邮箱", "用户名", "社交ID", "社交类型"]
CTYPE_REFLECT = {
"fb": "facebook",
"tw": "twitter",
"ins": "instagram",
"ly": "linkedln",
"voxer": "voxer",
"********": "********",
"ws": "whatsapp"
}
class StoreToXML(object):
def __init__(self, data, sheet_name="ALL_INFO"):
self.data = data
self.sheet_name = sheet_name
self._create_xml()
def paser_xml(self):
return self._save()
def _create_xml(self):
self.wb = Workbook()
self.ws = self.wb.create_sheet(self.sheet_name, 0)
def _save(self):
self.ws.append(order_list)
for onr in self.data:
name = onr.get("name", "")
addr = onr.get("location", "")
birthday = onr.get("birthday", "")
gender = onr.get("gender", "")
tel = onr.get("tel", "")
email = onr.get("email", "")
uname = onr.get("uname", "")
cid = onr.get("cid", "")
ctype = onr.get("ctype", "")
ctype = CTYPE_REFLECT.get(ctype, "")
row = [name, addr, birthday, gender, tel, email, uname, cid, ctype]
_row = []
for i in row:
if isinstance(i, list):
e = "\n".join(i)
_row.append(e)
elif isinstance(i, str):
_row.append(i)
else:
_row.append("")
self.ws.append(_row)
u = uuid.uuid4()
name = str(u) + ".xlsx"
self.wb.save(os.path.join(XML_DIRS, name))
url = "http://{ip}/xml/{name}".format(ip=get_ip(), name=name)
return url
if __name__ == '__main__':
info_list = [
{
"name": "sb",
"gender": "male"
},
{
"name": "sb4",
"location": "male",
"email": [
"[email protected]",
"[email protected]",
]
},
{
"uname": "fsafa",
"cid": "414155232",
"ctype": "fb"
}
]
s = StoreToXML(info_list)
res = s.paser_xml()
print(res)
推荐阅读