要在Django中读取Excel(xlsx)文件并在表格中显示,你需要使用一些库来处理Excel文件和表格显示
首先,确保已经安装了所需的库:
pip install openpyxl django-import-export
接下来,按照以下步骤操作:
settings.py
中添加import_export
到INSTALLED_APPS
:INSTALLED_APPS = [
# ...
'import_export',
]
# models.py
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
# resources.py
from import_export import resources
from .models import Person
class PersonResource(resources.ModelResource):
class Meta:
model = Person
views.py
中,创建一个视图来处理文件上传和表格显示:# views.py
from django.shortcuts import render
from .models import Person
from .resources import PersonResource
def upload_excel(request):
if request.method == 'POST':
person_resource = PersonResource()
result = person_resource.import_data(request.FILES['file'], dry_run=True)
if result.has_errors():
# 处理错误
pass
else:
person_resource.import_data(request.FILES['file'], dry_run=False)
persons = Person.objects.all()
return render(request, 'table.html', {'persons': persons})
return render(request, 'upload.html')
def table(request):
persons = Person.objects.all()
return render(request, 'table.html', {'persons': persons})
upload.html
用于上传文件,table.html
用于显示表格:<!-- upload.html -->
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file">
<button type="submit">上传</button>
</form>
<!-- table.html -->
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</4>
</thead>
<tbody>
{% for person in persons %}
<tr>
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
urls.py
中添加URL,以便访问视图:# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('upload/', views.upload_excel, name='upload_excel'),
path('table/', views.table, name='table'),
]
现在,你可以上传Excel文件并在表格中查看数据了。注意,这个示例仅适用于简单的Excel文件。对于更复杂的文件,你可能需要自定义导入过程。
领取专属 10元无门槛券
手把手带您无忧上云