1、導(dǎo)入需要的包
import xlrd
import datetime
2、編寫一個(gè)用于導(dǎo)入excel文件的裝飾器
# A decoration: import excel file
def import_excel_file(fn):
@functools.wraps(fn)
def wrapper(request, *args, **kwargs):
# 檢查導(dǎo)入的文件請(qǐng)求是否合法,文件是否能收到
try:
excel = request.FILES['excel']
except MultiValueDictKeyError:
return render(request, '400.html', {
'err': '數(shù)據(jù)導(dǎo)入出錯(cuò):沒(méi)有發(fā)現(xiàn)需要的導(dǎo)入的文件,請(qǐng)選擇導(dǎo)入的文件,再試一下!',
'back_url': request.session.get('back_url')
})
except AttributeError:
return render(request, '400.html', {
'err': '數(shù)據(jù)導(dǎo)入出錯(cuò):request沒(méi)有excel參數(shù),請(qǐng)聯(lián)系管理員!',
'back_url': request.session.get('back_url')
})
except KeyError:
return render(request, '400.html', {
'err': '數(shù)據(jù)導(dǎo)入出錯(cuò):request沒(méi)有excel參數(shù),請(qǐng)聯(lián)系管理員!',
'back_url': request.session.get('back_url')
})
# 驗(yàn)證導(dǎo)入的文件是否為合法的表格文件
try:
validate_excel(excel)
except ValidationError:
return render(request, '400.html', {
'err': '導(dǎo)入excel數(shù)據(jù)出錯(cuò):導(dǎo)入的文件< %s >格式不對(duì),請(qǐng)確保文件后綴是xls、xlsx 或csv!' % excel.name,
'back_url': request.session.get('back_url')
})
else:
data = xlrd.open_workbook(filename=None, file_contents=excel.read())
table = data.sheets()[0]
n_rows = table.nrows
return fn(request, *args, **kwargs, table=table, n_rows=n_rows)
return wrapper
3、編寫一個(gè)轉(zhuǎn)換單元格數(shù)據(jù)格式的工具函數(shù)
# A function tool: convert the type of cell while reading dates from import excel file
# Parameter: cell object which will be converted
# Return: right data type for python
def convert_cell_type_from_import_excel(_cell):
# 單元格的ctype屬性為0時(shí),對(duì)應(yīng)的python格式為空字符串:''
if _cell.ctype == 0:
return ''
# 單元格的ctype屬性為2時(shí),對(duì)應(yīng)的python格式為float和int
# 手動(dòng)做以下判斷將int類型分離出來(lái)
elif _cell.ctype == 2 and _cell.value % 1 == 0.0:
return int(_cell.value)
# 單元格的ctype屬性為3時(shí),對(duì)應(yīng)的python格式為datetime
elif _cell.ctype == 3:
return datetime.date(*xlrd.xldate_as_tuple(_cell.value, 0))
# 單元格的ctype屬性為4時(shí),對(duì)應(yīng)的python格式為Bool
elif _cell.ctype == 4:
return True if _cell.value == 1 else False
# 單元格的ctype屬性為1時(shí),對(duì)應(yīng)的python格式為字符串
# 默認(rèn)返回字符串和ctype=2時(shí)的float類型的內(nèi)容
else:
return _cell.value
4、編寫實(shí)際讀取excel的處理函數(shù)(需用上述裝飾器進(jìn)行裝飾)
@import_excel_file
def import_product_standard(request, table=None, n_rows=None):
for i in range(1, n_rows):
try:
# 使用工具函數(shù) "convert_cell_type_from_import_excel" 將每個(gè)cell對(duì)象轉(zhuǎn)換成相應(yīng)的Python格式
dic = {'ps_name': str(convert_cell_type_from_import_excel(table.cell(i, 0))).strip()[:50],
'jspl': str(convert_cell_type_from_import_excel(table.cell(i, 1))).strip()[:50],
'wspl': str(convert_cell_type_from_import_excel(table.cell(i, 2))).strip()[:50],
'jsqsbs': str(convert_cell_type_from_import_excel(table.cell(i, 3))).strip()[:50],
'wsqsbs': str(convert_cell_type_from_import_excel(table.cell(i, 4))).strip()[:50],
'jsdskz': str(convert_cell_type_from_import_excel(table.cell(i, 5))).strip()[:50],
'wsdskz': str(convert_cell_type_from_import_excel(table.cell(i, 6))).strip()[:50],
'jsdsql': str(convert_cell_type_from_import_excel(table.cell(i, 7))).strip()[:50],
'wsdsql': str(convert_cell_type_from_import_excel(table.cell(i, 8))).strip()[:50],
'dbjxql': str(convert_cell_type_from_import_excel(table.cell(i, 9))).strip()[:50],
'dbwxql': str(convert_cell_type_from_import_excel(table.cell(i, 10))).strip()[:50],
'dbpfkz': str(convert_cell_type_from_import_excel(table.cell(i, 11))).strip()[:50],
'dbjm': str(convert_cell_type_from_import_excel(table.cell(i, 12))).strip()[:50],
'dbwm': str(convert_cell_type_from_import_excel(table.cell(i, 13))).strip()[:50]}
......