在Django中将一栏中的文本从Excel分解成两个模型,可以通过以下步骤实现:
django-admin startproject project_name
from django.db import models
class Column1(models.Model):
text = models.CharField(max_length=255)
class Column2(models.Model):
text = models.CharField(max_length=255)
openpyxl
。可以通过以下命令安装该库:pip install openpyxl
from django.shortcuts import render
from openpyxl import load_workbook
from .models import Column1, Column2
def process_excel(request):
if request.method == 'POST' and request.FILES['excel_file']:
excel_file = request.FILES['excel_file']
wb = load_workbook(excel_file)
sheet = wb.active
for row in sheet.iter_rows(values_only=True):
column1_text = row[0]
column2_text = row[1]
column1 = Column1.objects.create(text=column1_text)
column2 = Column2.objects.create(text=column2_text)
return render(request, 'success.html')
return render(request, 'upload.html')
upload.html示例:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="excel_file">
<button type="submit">上传</button>
</form>
success.html示例:
<h1>处理成功!</h1>
from django.urls import path
from .views import process_excel
urlpatterns = [
path('process-excel/', process_excel, name='process_excel'),
]
现在,当访问/process-excel/
时,将显示一个上传Excel文件的表单。上传文件后,Django将读取Excel文件中的数据,并将其分解到Column1和Column2模型中。处理成功后,将显示处理成功的页面。
请注意,以上代码仅为示例,实际应用中可能需要根据具体需求进行适当的修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云