当前位置:网站首页>Detailed steps for Django to upload excel tables and write data to the database
Detailed steps for Django to upload excel tables and write data to the database
2022-06-30 19:54:00 【1024 Q】
Preface :
One 、 Upload files :
Two 、 analysis excel Import database
Preface :Recently, the leaders of the company need to count the percentage of working hours spent by the technology department in each business line , and jira Current Tempo The plug-in can only count individual man hours . So I wrote a report tool , take jira Personal hours exported from excel form Import database , The proportion of working hours for processing various businesses at the back end . Later jira Of API file , Give up the previous idea , Call directly jira API Processing data , Let's not talk about this first . This blog mainly introduces Django Upload files , And then parse excel Import database .
One 、 Upload files :Upload the file to the specified path of the server , It's very simple , There are three steps :
1. To configure setting.py
# File upload configuration UPLOAD_ROOT = os.path.join(BASE_DIR,'upload')2. The front-end code is as follows , Use <form> Form submission ,"/upload/" Routing is configured in urls in , I don't want to say more about this .
{% extends 'base.html' %}{% block content %}<body> <form id="form" enctype="multipart/form-data" action="/upload/" method="post"> <p><input type="file" name="file"></p> <input type="submit" name=" Submit "> </form></body>{% endblock %}3. The back-end code is as follows , This code can upload files of any format , File type not verified .
@csrf_exemptdef upload(request): # root name take file Value file = request.FILES.get('file') logger.log().info('uplaod:%s'% file) # establish upload Folder if not os.path.exists(settings.UPLOAD_ROOT): os.makedirs(settings.UPLOAD_ROOT) try: if file is None: return HttpResponse(' Please select the file to upload ') # Loop binary write with open(settings.UPLOAD_ROOT + "/" + file.name, 'wb') as f: for i in file.readlines(): f.write(i) except Exception as e: return HttpResponse(e) return HttpResponse(' Upload successful ') Two 、 analysis excel Import database 1. After file upload , Next, read the data just uploaded to the server excel form , Then write it to the database . So the whole back-end code is like this :
# take excel Data writing mysqldef wrdb(filename): # Open upload excel form readboot = xlrd.open_workbook(settings.UPLOAD_ROOT + "/" + filename) sheet = readboot.sheet_by_index(0) # obtain excel Rows and columns of nrows = sheet.nrows ncols = sheet.ncols print(ncols,nrows) sql = "insert into working_hours (jobnum,name,workingtime,category,project,date,createtime) VALUES" for i in range(1,nrows): row = sheet.row_values(i) jobnum = row[4] name = row[5] workingtime = row[2] category = row[8] project = row[1] date = xldate_as_datetime(row[3],0).strftime('%Y/%m/%d') values = "('%s','%s','%s','%s','%s','%s','%s')"%(jobnum,name,workingtime,category,project,date,datetime.datetime.now()) sql = sql + values +"," # In order to improve operation efficiency , One time data insert Enter database sql = sql[:-1] # Write to database # DataConnection It is a custom public module , Using a third-party library , To operate the database . of no avail ORM , There will be group by Etc sql It's not easy to operate . DataConnection.MysqlConnection().insert('work',sql)@csrf_exemptdef upload(request): # root name take file Value file = request.FILES.get('file') print('uplaod:%s'% file) # establish upload Folder if not os.path.exists(settings.UPLOAD_ROOT): os.makedirs(settings.UPLOAD_ROOT) try: if file is None: return HttpResponse(' Please select the file to upload ') # Loop binary write with open(settings.UPLOAD_ROOT + "/" + file.name, 'wb') as f: for i in file.readlines(): f.write(i) # write in mysql wrdb(file.name) except Exception as e: return HttpResponse(e) return HttpResponse(' Successful import ')2. After data import , Through some processing, we can get the data we want . The pie chart of one of the reports :

This is about Django Upload excel This is the end of the article about tables and writing data to the database , More about Django Upload excel Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !
边栏推荐
- Playwright - 滚动条操作
- Application of VoIP push in overseas audio and video services
- S7-1500 PLC之间进行TCP通信的具体方法和步骤详解(图文)
- 事件队列、微任务与宏任务的理解和面试题
- 更智能!AIRIOT加速煤炭行业节能减排升级
- Advanced skills of testers: a guide to the application of unit test reports
- Kubevela 1.4: make application delivery safer, easier to use, and more transparent
- KubeVela 1.4:让应用交付更安全、上手更简单、过程更透明
- 派尔特医疗在港交所招股书二次“失效”,上市计划实质性延迟
- [multithreading] use the thread pool to implement a simple thread pool
猜你喜欢
![[solved] how does Tiktok cancel paying attention to the cancelled account](/img/1f/7b0bd2c0f69f7f3d1c25c426cc5771.png)
[solved] how does Tiktok cancel paying attention to the cancelled account

Wechat applets - basics takes you to understand the life cycle of applets (2)

Advanced skills of testers: a guide to the application of unit test reports

2022年高考都结束了,还有人真觉得程序员下班后不需要学习吗?

VoIP Push 在海外音视频业务中的应用

4.3寸触控屏12路控制端口可编程网络中控支持5台中控主机相互备份

KubeVela 1.4:让应用交付更安全、上手更简单、过程更透明

企业中台规划和IT架构微服务转型

昔日果汁大王,16个亿卖了

【已解决】抖音如何取消关注已注销的账户
随机推荐
WeakSet
CV+Deep Learning——网络架构Pytorch复现系列——basenets(BackBones)(一)
解决arm_release_ver of this libmali is ‘g2p0-01eac0‘,rk_so_ver is ‘4‘,libgl1-mesa-dev不会被安装,存在未满足的依赖关系
Unity 如何拖拉多个组件中的一个
内存数据库如何发挥内存优势?
RP prototype resource sharing - shopping app
8 - 函数
更智能!AIRIOT加速煤炭行业节能减排升级
PS2手柄-1「建议收藏」
VR全景添加对比功能,让差异化效果展示更直观!
Go language learning tutorial (13)
小学期,第三场-下午:WEB_sessionlfi
Code shoe set - mt3111 · assignment
VR云展厅如何给线下实体带来活力?有哪些功能?
数据智能——DTCC2022!中国数据库技术大会即将开幕
S7-1500 PLC之间进行TCP通信的具体方法和步骤详解(图文)
MySQL数据库查询优化
c语言数组截取,C# 字符串按数组截取方法(C/S)
英语没学好到底能不能做coder,别再纠结了先学起来
VR全景拍摄为什么要加盟?巧借资源实现共赢