我有一个包含各种列和行的excel文件。我上传此文件并保存数据 在数据库中。但我遇到了问题,需要帮助解决这个问题: -
1)上传具有相同名称但内容不同的文件上传以前的文件数据。
所以,假设我上传abc.xls有3行,它上行3行,但如果我上传另一个文件,其中10行具有相同的名称abc.xls,它会显示以前上传的文件的结果,只显示3个结果。< / p>
我尝试过像我这样的文件或目录。但是我没有这样的文件或目录。
# Models.py
class ExcelFile(models.Model):
excel_file = models.FileField(upload_to='documents/')
class Meta:
verbose_name = 'ExcelFile'
verbose_name_plural = 'ExcelFiles'
def __unicode__(self):
return self.excel_file.name
在管理员中,我看到文件已经是唯一的,如abc_1.xls,abc_2.xls等。 这是我的代码
#views.py
if request.method == "POST":
form_data = ImportExcelForm(request.POST, request.FILES)
if form_data.is_valid():
cd = form_data.cleaned_data
file_obj, created = ExcelFile.objects.get_or_create(excel_file=cd['excel_file'])
try:
data_list = excel_parser(cd['excel_file'].name.replace(" ", "_"))
except:
data_list = excel_parser(get_correct_filename(cd['excel_file']))
########### and so on #######################
def get_correct_filename(filename):
replacements = {"(": "", ")": ""," ":"_"}
new_file = "".join(replacements.get(c, c) for c in filename.name)
return new_file
def excel_parser(filename):
"""
Excel file will first come here. It will be read sheetwise.
This functions will return a data list.
"""
file_path = settings.MEDIA_ROOT + 'documents/' + filename
#Here it is reading abc.xls only as the filename is abc.xls
book = open_workbook(file_path)
data_list = []
sheet_list = []
total_sheets = book.nsheets
for sheet in range(total_sheets):
sheet_counter = book.sheet_by_index(sheet)
data_list = extract_data(book,sheet)
sheet_list.append(data_list)
return sheet_list
答案 0 :(得分:0)
您必须在媒体目录中创建目录'uploads / logos'。你可以手动或自动完成:
How to check if a directory exists and create it if necessary?