关于读取excel 和 写excel
def sync_db(data_list):
'''Synchron potential student from excel to PrepareToCrm
'''
push_list = []
m_q = {i['mobile']: i['qudao_details'] for i in
PrepareToCrm.objects.values('mobile', 'qudao_details')}
[m_q.setdefault(i['phone'], i['qudao_details'])
for i in PrepareToCrm.objects.filter(phone__isnull=False).values(
'phone', 'qudao_details')]
[m_q.setdefault(i['other_phone'], i['qudao_details'])
for i in PrepareToCrm.objects.filter(other_phone__isnull=False).values(
'other_phone', 'qudao_details')] for data_dict in data_list:
try:
if data_dict['mobile'] == data_dict['phone']:
data_dict['phone'] = None
except KeyError:
data_dict['phone'] = None
try:
if data_dict['mobile'] == data_dict['other_phone']:
data_dict['other_phone'] = None
except KeyError:
data_dict['other_phone'] = None
try:
if data_dict['phone'] == data_dict['other_phone']:
data_dict['other_phone'] = None
except KeyError:
data_dict['other_phone'] = None mobile = str(data_dict['mobile']) if data_dict['mobile'] else None
phone = str(data_dict['phone']) if data_dict['phone'] else None
other_phone = str(
data_dict['other_phone']) if data_dict['other_phone'] else None mobiles = [i for i in [mobile, phone, other_phone] if i] if not mobiles:
data_dict['push_result'] = '啥电话都没有'
data_dict['feedback'] = True
else:
for mobile in mobiles:
if mobile not in m_q:
m_q[mobile] = data_dict['qudao_details']
else:
qudao_details = m_q[mobile]
data_dict['push_result'] = '重复推送({})'.format(
qudao_details)
data_dict['feedback'] = True
if not data_dict['create_user']:
data_dict['create_user'] = ''
push_list.append(PrepareToCrm(**data_dict)) PrepareToCrm.objects.bulk_create(push_list)
写入数据库
def prepare_crm_data_from_excel(request):
'''Get potential student from excel
'''
if request.method == 'POST':
user = request.user
result_dict = {}
if not request.FILES:
return HttpResponse('请选择上传文件')
f = request.FILES['file']
if str(f).split('.')[-1] not in ['xlsx', 'xls']:
return HttpResponse('请上传(xlsx, xls)')
wb2 = openpyxl.load_workbook(f)
fields = []
datas = []
crm_list = []
for table in wb2.worksheets: # .xsl里的每个sheet
for row in table.rows: # row 每一行 数据
if not fields: # 这个fields只有字头
fields.extend([column.value for column in row])
continue
d = {}
index = 0
for column in row:
try:
d[index] = column.value.strip()
except AttributeError:
d[index] = column.value
index += 1
if any(d.values()):
datas.append(d) order_fields = {i[0]: i[1] for i in enumerate(fields)} for data in datas:
d = {'user': user}
for k, v in list(data.items()):
key_index = order_fields[k]
if not key_index:
continue
crm_key = ALL_FIELDS[key_index]
d[crm_key] = v
crm_list.append(d)
sync_db(crm_list) result_dict['result'] = 'ok'
return Response(result_dict, status=status.HTTP_200_OK) html = """<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" /><input type="submit"/></form>"""
response = HttpResponse(html)
response["Allow-Control-Allow-Origin"] = '*'
return response
上传读取excel
ALL_FIELDS = {i.verbose_name: i.name for i in
PrepareToCrm._meta.fields if i.name not in EXCLUDES} EXCLUDES = [
'id', 'push_result', 'success', 'pushing', 'exported', 'upload_time'
]
程序写成Excel 发送邮箱
def run():
EXCEL_CACHE_PATH = "/tmp/_BI_EXCEL_CACHE"
xlsxfile = '{}/push_result.xlsx'.format(EXCEL_CACHE_PATH) custom_set = PrepareToCrm.objects.filter(user__isnull=False, feedback=True)
if custom_set.exists():
user_list = set([custom_obj.user_id for custom_obj in custom_set])
for user_id in user_list:
mobile_set = custom_set.filter(user_id=user_id).values('mobile', 'name', 'success', 'apply_contry')
result_list = [['学生姓名', '电话', '申请国家', '申请项目', '跟进顾问', '分校',
'是否成功推送', 'BI客户状态', 'CRM客户状态', '备注'], ]
for mo_name in mobile_set:
mobile = mo_name.get('mobile')
name = mo_name.get('name')
success = '推送成功' if mo_name.get('success') else '推送失败'
apply_contry = mo_name.get('apply_contry') crp_status = '无状态'
crm_status = '无状态' ad_set = Advisor_potential_student.objects.filter(
Q(mobile__contains=mobile) | Q(phone__contains=mobile) |
Q(other_phone__contains=mobile)).values('pk', 'status', 'education', 'advisor__address_city',
'advisor__full_name')
crm_set = CrmDB.objects.using('crm').filter(
Q(mobile__contains=mobile) | Q(phone__contains=mobile) |
Q(other_phone__contains=mobile)).values('latest_status') education = '无'
address_city = '无'
full_name = '无'
con_l = []
con_str = ''
if ad_set.exists():
status_num = ad_set[0]['status']
education = ad_set[0]['education']
address_city = ad_set[0]['advisor__address_city']
full_name = ad_set[0]['advisor__full_name']
potential_id = ad_set[0]['pk']
crp_status = SOURCE_STATUS.get(status_num) remark_set = Advisor_student_remark.objects.filter(potential_id=potential_id).values('create_at', 'content').order_by('-create_at') for remark in remark_set:
time = remark['create_at'].strftime('%Y-%m-%d %H:%M:%S')
content = remark['content']
w_content = '【' + time + '】' + ' ' + content + '\n' # 拼接备注的字符串
con_l.append(w_content)
content_str = con_str.join(con_l)
else:
content_str = '无' if crm_set.exists():
try:
status_num = crm_set[0]['latest_status']
crm_status = crm_status_dict.get(int(status_num))
except Exception as e:
crm_status = '无状态'
result_list.append(
[name, mobile, apply_contry, education, full_name, address_city, success, crp_status, crm_status, content_str]) xlsx = openpyxl.Workbook()
table = xlsx.active
table.title = 'data' for line in result_list:
table.append(line) xlsx.save(xlsxfile)
send_mail(user_id)
def send_mail(user_id):
email_obj = User.objects.filter(id=user_id).values('email')[0]
to_email = email_obj['email']
if not to_email:
return
SMTP_HOST = "xxxxxx.qq.com"
AUTH_USER = "xxxxxt@xxxxxx.com"
AUTH_PASS = "xxxxxxxxxxxx123" email = MIMEMultipart() to_list = [
to_email
] from_addr = 'xxxxxxxxxxxx.com'
email['From'] = from_addr
email['To'] = Header(COMMASPACE.join(to_list), 'utf8')
email['Subject'] = Header('推送失败反馈', 'utf-8')
xlsxfile = '/tmp/_BI_EXCEL_CACHE/push_result.xlsx'
with open(xlsxfile, 'rb') as f:
attach = MIMEApplication(f.read())
attach.add_header('Content-Disposition', 'attachment',
filename='push_result.xlsx')
email.attach(attach) smtp = smtplib.SMTP_SSL(SMTP_HOST)
smtp.login(AUTH_USER, AUTH_PASS)
smtp.sendmail(from_addr, to_list, email.as_string())
关于读取excel 和 写excel的更多相关文章
- C# 读带复选框的excel,写excel并设置字体、边框、背景色
这是一篇excel读写功能大汇总,通过C#调用Microsoft.Office.Interop.Excel.dll才能完成任何复杂格式excel的读写操作. 本文需要读取的excel格式如下: 可见表 ...
- python中使用xlrd读excel使用xlwt写excel
原文地址 :http://www.bugingcode.com/blog/python_xlrd_read_excel_xlwt_write_excel.html 在数据分析和运营的过程中,有非常多的 ...
- Python:使用第三方库xlwt来写Excel
继上一篇文章使用xlrd来读Excel之后,这一篇文章就来介绍下,如何来写Excel,写Excel我们需要使用第三方库xlwt,和xlrd一样,xlrd表示read xls,xlwt表示write x ...
- java的poi技术写Excel的Sheet
在这之前写过关于java读,写Excel的blog如下: Excel转Html java的poi技术读,写Excel[2003-2007,2010] java的poi技术读取Excel[2003-20 ...
- java的poi技术读,写Excel[2003-2007,2010]
在上一篇blog:java的poi技术读取Excel[2003-2007,2010] 中介绍了关于java中的poi技术读取excel的相关操作 读取excel和MySQL相关: java的poi技术 ...
- 读取和导出下载 excel 2003,2007 资料
protected void Page_Load(object sender, EventArgs e) { //直接在bin add referece search Microsoft.Office ...
- jxl读写excel, poi读写excel,word, 读取Excel数据到MySQL
这篇blog是介绍: 1. java中的poi技术读取Excel数据,然后保存到MySQL数据中. 2. jxl读写excel 你也可以在 : java的poi技术读取和导入Excel了解到写入Exc ...
- Pandas 基础(4) - 读/写 Excel 和 CSV 文件
这一节将分别介绍读/写 Excel 和 CSV 文件的各种方式: - 读入 CSV 文件 首先是准备一个 csv 文件, 这里我用的是 stock_data.csv, 文件我已上传, 大家可以直接下载 ...
- python读、写、修改、追写excel文件
三个工具包 python操作excel的三个工具包如下 xlrd: 对excel进行读相关操作 xlwt: 对excel进行写相关操作 xlutils: 对excel读写操作的整合 注意,只能操作.x ...
随机推荐
- Nginx整合tomcat,实现反向代理和负载均衡
1.Nginx与Tomcat整合,通过Nginx反向代理Tomcat. Nginx安装路径为:/usr/local//nginx 首先切换路径到:/usr/local//nginx/conf通过命令 ...
- 后缀自动机(SAM)学习笔记
目录 定义 SAM 的状态集 一些性质 SAM 的后缀链接 SAM 的转移函数 一些性质 算法构造 构造方法 时间复杂度证明 状态的数量 转移的数量 代码实现 实际应用 统计本质不同的子串个数 计算任 ...
- Linux系统初始化配置项(centos7)
主机刚安装完系统,会做一些配置上的优化. 修改时区 通过命令将时区设置为亚洲/上海. timedatectl set-timezone Asia/Shanghai #centos7 cp /usr/s ...
- 洛谷 P4302 【[SCOI2003]字符串折叠】
又来填一个以前很久很久以前挖的坑 首先如果先抛开折叠的内部情况不谈,我们可以得到这样的一个经典的区间DP的式子 $ f[l][r]=min(f[l][r],f[l][k]+f[k+1][r])(l&l ...
- I2C 总线原理与架构
一.I2C总线原理 I2C是一种常用的串行总线,由串行数据线SDA 和串行时钟线SCL组成.I2C是一种多主机控制总线,它和USB总线不同,USB是基于master-slave机制,任何设备的通信必须 ...
- (一)Qt5模块,QtCreator常用快捷键,命名规范
常用快捷键 1)帮助文件:F1 (光标在函数名字或类名上,按 F1 即可跳转到对应帮助文档,查看其详细用法) 2).h 文件和对应.cpp 文件切换:F4 3)编译并运行:Ctrl + R 4)函数声 ...
- Memcached操作
标准协议和字段 Memcached的标准协议字段包含以下部分: 键,key,任意字符,最大250字节,不能有空格和换行 标志位,32比特,不能为0 超时时间,单位是秒,0代表永不超时,最长30天,30 ...
- building tool的简单了解
java常用的三种构建工具: Apache Maven ——主要用于构建Java项目的自动化工具. NetBeans IDE 支持 Maven 构建系统,可帮助您管理项目的依赖关系.构建.报告和文档. ...
- Numpy系列(五)- 复制和视图
当计算和操作数组时,它们的数据有时被复制到新的数组中,有时不复制.这里我们做个区分. 完全不复制 简单赋值不会创建数组对象或其数据的拷贝. import numpy as np a = np.aran ...
- C++回顾day03---<异常>
一:传统错误处理机制(C中通过函数返回来处理) int CalcRes(int n, int m, char ch, int& res) { ; switch (ch) { case '+': ...