excel就像左边的图片有3列.
当插入数据库时,我需要手动添加2列,如右图所示,最后在数据库中共插入5列.这些2个附加列信息从其他数据库中获取.
另一个功能是,如果已有文件,新上传的文件将覆盖现有文件.[下面的views.py中的片段]
我已经尝试了两个3方工具,但没有工作,所以也许只是使用django中嵌入的工具更好.
版本:Python 2.7.Excel 2013. Django1.8.
任何帮助都非常感谢.Hope可以提供有关如何附加这两列的详细信息片段:
uploader = request.session['uploader'] Date=request.session['date']
forms.py
from django.core.files.storage import FileSystemStorage from financialdata.storage import OverwriteStorage class XXXXDataForm(forms.Form): XXXXfile=forms.FileField(label='Select a file')
views.py
from django.core.files.storage import FileSystemStorage def import_data(request): if request.method == "POST": form = XXXXForm(request.POST,request.FILES) if form.is_valid(): newdoc= XXXX(docfile=request.FILES['docfile']) newdoc.save() return HttpResponseRedirect(reverse('homepage')) else: return HttpResponseBadRequest() else: form = XXXXForm() return render_to_response( 'dataentry.html', { 'form': form, 'title': 'Import excel data into database example', 'header': 'Please upload XXXX.xlsx:', 'message': 'File Saved!' }, context_instance=RequestContext(request)) class OverwriteStorage(FileSystemStorage): def _save(self, name, content): if self.exists(name): self.delete(name) return super(OverwriteStorage, self)._save(name, content) def get_available_name(self, name): return name
小智.. 6
可能是这样的:
我没有运行我的代码,这是一个例子
if request.method == "POST": form = XXXXForm(request.POST,request.FILES) if form.is_valid(): docfile=request.FILES['docfile']if isinstance(docfile, (InMemoryUploadedFile, TemporaryUploadedFile)): book = xlrd.open_workbook(file_contents=docfile.read(), formatting_info=True, on_demand=True) else: book = xlrd.open_workbook(filename=docfile, formatting_info=True, on_demand=True) sheet = book.sheet_by_index(0) new_csv_file = csv.writer(open('new_filename', 'w')) # read file for line in range(1, sheet.nrows): new_row = [request.session.get('uploader'), request.session.get('date')] new_row.extend(sheet.row_values(line)) new_csv_file.writerow(new_row)...
1> 小智..:可能是这样的:
我没有运行我的代码,这是一个例子
if request.method == "POST": form = XXXXForm(request.POST,request.FILES) if form.is_valid(): docfile=request.FILES['docfile']if isinstance(docfile, (InMemoryUploadedFile, TemporaryUploadedFile)): book = xlrd.open_workbook(file_contents=docfile.read(), formatting_info=True, on_demand=True) else: book = xlrd.open_workbook(filename=docfile, formatting_info=True, on_demand=True) sheet = book.sheet_by_index(0) new_csv_file = csv.writer(open('new_filename', 'w')) # read file for line in range(1, sheet.nrows): new_row = [request.session.get('uploader'), request.session.get('date')] new_row.extend(sheet.row_values(line)) new_csv_file.writerow(new_row)...