Django前端页面导入表格,导入数据库,并在前端页面展示的代码
时间: 2023-06-09 19:06:38 浏览: 147
把表格内容导入数据库
很抱歉,作为AI助手,我无法知晓你与我之间的约定和要求。但是,我可以为你提供一份Django导入表格、导入数据库,并在前端页面展示的代码示例,供参考:
首先,需要安装一些Python包:
```bash
pip install django
pip install openpyxl
pip install pandas
```
接下来,创建一个Django项目,然后在`urls.py`中添加以下路由:
```python
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('upload/', views.upload, name='upload'),
]
```
在`views.py`中添加以下代码:
```python
# views.py
import pandas as pd
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import ExcelForm
from .models import ExampleModel
def index(request):
data = ExampleModel.objects.all()
return render(request, 'index.html', {'data': data})
def upload(request):
if request.method == 'POST':
form = ExcelForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
# 读取Excel文件
xls = pd.ExcelFile(file)
df = xls.parse('Sheet1')
# 保存数据到数据库中
for index, row in df.iterrows():
data = ExampleModel()
data.col1 = row['col1']
data.col2 = row['col2']
data.col3 = row['col3']
data.save()
return HttpResponseRedirect('/')
else:
form = ExcelForm()
return render(request, 'upload.html', {'form': form})
```
在`models.py`文件中创建一个模型:
```python
# models.py
from django.db import models
class ExampleModel(models.Model):
col1 = models.CharField(max_length=100)
col2 = models.CharField(max_length=100)
col3 = models.CharField(max_length=100)
```
接下来,创建一个表单`forms.py`:
```python
# forms.py
from django import forms
class ExcelForm(forms.Form):
file = forms.FileField()
```
最后,在`templates`目录中创建两个HTML文件,`index.html`和`upload.html`,分别用于显示数据和上传文件。
`index.html`代码:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{ item.col1 }}</td>
<td>{{ item.col2 }}</td>
<td>{{ item.col3 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
```
`upload.html`代码:
```html
<!-- upload.html -->
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>
```
以上代码可以实现将Excel文件导入数据库,并在前端页面展示数据。但应根据实际情况进行修改和适配。希望能对你有所帮助!
阅读全文