我有一個excel文件與各種各樣的行和列。我上傳這個文件並將數據 保存在數據庫中。但我在解決這個問題時遇到問題並需要幫助: -文件上傳數據
1)上傳具有相同名稱但具有不同內容的文件將上一個文件數據。
所以說,我上傳abc.xls有3行它uplods 3行,但如果我上傳另一個文件與10行具有相同的名稱abc.xls它顯示以前上傳的文件的結果,並只顯示3結果。
我試過了獨特的文件,但後來我沒有這樣的文件或目錄。
# 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
你是如何處理上傳的? – miki725
你現在可以看到我的代碼,它會選擇相同的文件,儘管它正在上傳已創建的db – user734353