当前位置:网站首页>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 !
边栏推荐
猜你喜欢

测试人进阶技能:单元测试报告应用指南

Spark - 一文搞懂 Partitioner

Kubevela 1.4: make application delivery safer, easier to use, and more transparent

Application of VoIP push in overseas audio and video services

标配10个安全气囊,奇瑞艾瑞泽8安全防护无死角

VR云展厅如何给线下实体带来活力?有哪些功能?

8 - function

VR全景拍摄为什么要加盟?巧借资源实现共赢

RP原型资源分享-购物类App

A necessary tool for testing -- postman practical tutorial
随机推荐
A necessary tool for testing -- postman practical tutorial
Taiwan SSS Xinchuang sss1700 replaces cmedia cm6533 24bit 96KHz USB audio codec chip
腾讯会议应用市场正式上线,首批入驻超20款应用
启动PHP报错ERROR: [pool www] cannot get uid for user ‘@[email protected]’
SQL continuous login problem
笔记软件的历史、选择策略以及深度评测
How does an in memory database take advantage of memory?
JVM FAQs
超视频时代的音视频架构建设|Science和英特尔联袂推出“架构师成长计划”第二季
Smarter! Airiot accelerates the upgrading of energy conservation and emission reduction in the coal industry
Kubevela 1.4: make application delivery safer, easier to use, and more transparent
Tencent conference application market was officially launched, with more than 20 applications in the first batch
Advanced skills of testers: a guide to the application of unit test reports
The prospectus of pelt medical was "invalid" for the second time in the Hong Kong stock exchange, and the listing plan was substantially delayed
Whether the SQL is indexed
Abaqus 2022软件安装包和安装教程
SM2246EN+闪迪15131
测试人进阶技能:单元测试报告应用指南
PS2手柄-1「建议收藏」
RP prototype resource sharing - shopping app