django 解析上传xls文件
1.解析上传数据
class DataUploadAPIView(APIView):
# authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
# permission_classes = (IsAuthenticated,) @transaction.atomic
def post(self, request, *arge, **kwargs):
'''上传数据'''
data = request.data
# {'type': ['0'], 'table_name': ['16'], 'new_table_name': ['11'], 'field_name': ['id'], 'versions': ['0'], 'versions_name': ['222'], 'Fdata': [<InMemoryUploadedFile: drug_base_copy2.xls (application/vnd.ms-excel)>]}
filed_name = request.data['Fdata']
if not filed_name:
raise Forbidden('没有获取到文件')
destination = open(
os.path.join(os.path.dirname(os.path.abspath(__file__)) + '\\excel_upload\\', filed_name.name),
'wb+') # 打开特定的文件进行二进制的写操作
for chunk in filed_name.chunks(): # 分块写入文件
destination.write(chunk)
destination.close()
type_name = data['type']
table_name_id = data['table_name']
new_table_name = data['new_table_name']
field_name = data['field_name']
versions = data['versions']
versions_name = data['versions_name']
table_name = 'database_data_' + DrugTables.objects.filter(pk=table_name_id)[0].table_name
if int(type_name) == int(2):
cursor = connection.cursor()
cursor.execute(f'CREATE TABLE database_data_{new_table_name} LIKE {table_name};')
table_datas = DrugTables.objects.filter(table_name=table_name.replace('database_data_', ''))[0]
DrugTables.objects.create(table_name=new_table_name, table_comment=table_datas.table_comment,
# drug_cls=table_datas.drug_cls, user_cls=table_datas.user_cls)
drug_cls=table_datas.drug_cls, user_cls=request.user)
if str(versions) == str(0):
versions = versions_name
# 读取文件数据
workbook = xlrd.open_workbook(
os.path.join(os.path.dirname(os.path.abspath(__file__)) + '\\excel_upload\\', filed_name.name))
table = workbook.sheets()[0]
# 获取总行数
nrows = table.nrows
head_data = []
queryset = get_query_dawnload(connection, table_name, DATABASES['default']['NAME'])
for sql_info in queryset:
if sql_info['COLUMN_NAME'] != 'id' and sql_info['COLUMN_NAME'] != 'version':
head_data.append(sql_info['COLUMN_NAME']) # 设置标题字段 # 从第三行开始
cursor = connection.cursor()
for x in range(2, nrows):
row = table.row_values(x)
table_data = {}
# 获取数据字段
for i, info in enumerate(head_data):
ctype = table.cell(x, i).ctype
if ctype == 2 and row[i] % 1 == 0:
table_data[info] = int(row[i])
elif ctype == 3:
table_data[info] = xlrd.xldate_as_datetime(row[i], 0)
else:
table_data[info] = str(row[i])
if int(type_name) == int(0):
list_key = []
list_lalues = []
for key, lalues in table_data.items():
list_key.append(key)
list_lalues.append("'" + str(lalues) + "'")
# 拼接sql语句
sql_insert = 'insert into {}({}, version) values({}, "{}")'.format(table_name,
', '.join(list_key),
', '.join(list_lalues), versions)
elif int(type_name) == int(1):
list_lalues = []
field_value = ''
for key, lalues in table_data.items():
list_lalues.append(key + '=' + "'" + str(lalues) + "'")
if key == field_name:
field_value = lalues
lalues = ','.join(list_lalues)
sql_insert = f'update {table_name} set {lalues} where {field_name}="{field_value}" and version="{versions}"' elif int(type_name) == int(2):
list_key = []
list_lalues = []
for key, lalues in table_data.items():
list_key.append(key)
list_lalues.append("'" + str(lalues) + "'")
sql_insert = 'insert into database_data_{}({}, version) values({}, "{}")'.format(new_table_name,
', '.join(list_key),
', '.join(list_lalues),
versions) try:
cursor.execute(sql_insert)
except Exception as e:
raise Forbidden('上传解析失败,第{}指端长度超索引, 错误类型:{}'.format(x + 1, e))
return HttpResponse(json.dumps({"status": "上传数据成功", 'data': filed_name.name}), status=status.HTTP_200_OK)
django 解析上传xls文件的更多相关文章
- java上传xls文件
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System. ...
- Springboot/SpringMvc 读取上传 xls 文件内容
/** * 读取上传 xls 内容返回 * @param file * @return */@RequestMapping(value = "/read.xls")@Respons ...
- python发送post请求上传文件,无法解析上传的文件
前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...
- input file 上传 判断文件类型、路径是否为空
<html> <body bgcolor="white"> <TABLE cellSpacing=0 cellPadding=0 width=&quo ...
- SpringMVC文件上传 Excle文件 Poi解析 验证 去重 并批量导入 MYSQL数据库
SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库 /** * 业务需求说明: * 1 批量导入成员 并且 自主创建账号 * 2 校验数据格式 且 重复导入提示 已被 ...
- django上传excel文件
def uploadGrade(request): ''' 班级信息导入 :param request: :return: ''' if request.method == 'POST': f = r ...
- java上传excel文件及解析
java上传excel文件及解析 CreateTime--2018年3月5日16:25:14 Author:Marydon 一.准备工作 1.1 文件上传插件:swfupload: 1.2 文件上 ...
- java 解析上传的Excel文件
java poi解析上传的Excel文件 package com.zhl.push.Utils; /** * @Author TAO * @ClassName ExcelData * @Descrip ...
- DJANGO技巧两则:模拟MKDIR -P及配合NGINX上传大文件不使超时
这都是在开发当哪遇到的问题,网上转转,作个记录: http://blog.chinaunix.net/uid-25525723-id-1596574.html http://bookshadow.co ...
随机推荐
- [LeetCode] 483. Smallest Good Base 最小的好基数
For an integer n, we call k>=2 a good base of n, if all digits of n base k are 1. Now given a str ...
- 阿里开源的缓存框架JetCache
之前一直在用Spring Cache进行接口数据的缓存,主要是Spring Cache在对具体key缓存失效时间的设置不是很方法,还要自己去扩展,无意中发现了阿里的JetCache.大部分的需求都能满 ...
- thinkphp5.1 - twig模板-全局变量
thinkphp5.1 - twig模板-全局变量我们在定义 ccs 之类的静态文件的时候,经常会使用<link rel="stylesheet" href="__ ...
- oracle--数据库扩容后出现ORA-27102
一,问题描述 Connected to an idle instance. SQL> startup nomount ORA: obsolete or deprecated parameter( ...
- qt no doubments matching "ui..h" could be found
问题情境描述: 自己单独添加的UI文件,然后添加一个类来使用这个UI文件,第一次输入UI Form名称时是大写,被添加到工程里面就是大写, 大写的情况下,添加action转到槽就会提示这个错误. 修改 ...
- .NET CORE编写控制台程序应有的优雅姿势(转载)
原文地址:https://www.cnblogs.com/zuowj/p/11107243.html 本文所说的编写控制台程序应有的“正确”方法,我把正确二字加上引号,因为没有绝对的正确,因人而异,因 ...
- Windows10 64位部署odoo12开发环境
预装Windows10 64位家庭版电脑一台 2019年7月 安装Python,这里的版本选择上有个坑,不要装最新的Python 3.7.x,原因是odoo12依赖pillow 4.0.0库,而这个4 ...
- FFT(快速傅里叶变换)
FFT(快速傅里叶变换) 前置知识 \(1.复数\) \(2.单位根\) \(3.循环结构\) \(4.C++\) 1.复数 \(定义:形如a+bi的数,其中i^2=-1\) \(计算:1.(a+bi ...
- Spring Boot入门及第一个案例
一:SpringBoot是什么 springboot是对spring的缺点进行改善和优化,约定大于配置 开箱即用 没有代码生成 也无需xml 文件配置 可以修改属性值来满足需求 1) Spri ...
- nginx 指向本地目录
# 必须配置此目录 location /upload { root D:\\upload\\; rewrite break; }