1. 保存前端传过来的二进制Excel文件
import xlrd
file = self.request.FILES['excel_file']
url = settings.BASE_DIR + '/static/files/' + file.name
with open(url, 'wb')as f:
for data in file.chunks():
f.write(data)
2. 读取Excel文件
import xlrd
url = settings.BASE_DIR + '/static/files/' + file.name
# 打开指定路径的Excel文件
readbook = xlrd.open_workbook(url)
# 打开第一张表(一个Excel文件可以有多张表)
sheet = readbook.sheet_by_index(0)
# 获取行数
nrows = sheet.nrows
for x in range(1, nrows):
# row表示某一行的所有数据,是一个列表
row = sheet.row_values(x)
3. django实现将数据库中的数据导出到Excel文件。
views.py:
import xlwt
def loadfile(request):
# 指定数据类型
response = HttpResponse(content_type='application/ms-excel')
# 设置文件名称
response['Content-Disposition'] = 'attachment; filename="result.xls"'
# 创建工作簿
wb = xlwt.Workbook(encoding='utf-8')
# 创建表
ws = wb.add_sheet('Menu')
row_num = 0
font_style = xlwt.XFStyle()
# 二进制
font_style.font.bold = True
# 表头内容
columns = ['姓名', '性别', '年龄', '住址']
# 写进表头内容
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
# 获取数据库数据
rows = Msg.objects.all.values_list('name', 'sex', 'age', 'address')
# 遍历提取出来的内容
for row in rows:
row_num += 1
# 逐行写入Excel
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response
urls.py
from project.views import loadfile
urlpatterns = [
url(r'^loadfile/$', loadfile, name='下载')
]
读取excel中导入的时间
excel中导入的时间在读取的时候是一串数字,类似于456374.234134
读取方法是:
# 变为元祖,第二个参数有两种取值,0或者1,0是以1900-01-01为基准的日期,而1是1904-01-01为基准的日期。
wf_time = str(xlrd.xldate.xldate_as_datetime(Excel_time, 0))
但这样设置的话,如果传来的书正常的时间字符串,就会抛出异常
所以建议两种时间格式都要考虑进去.