经过实验,新建一个excel表格,该表格拥有7个sheet,每个sheet有800条数据,其中最后一个sheet为空。
首先使用openpyxl进行写入操作,代码如下:
book = openpyxl.Workbook()
auths = Auth.objects.filter(owner_id=1)
filename = '导出数据'
for auth in auths:
sheet = book.create_sheet(auth.name, index = 0)
sheet.append([
_("书名"),
_("作者"),
_("译者"),
_("出版社"),
_("序列号"),
_("总页数"),
])
objs = None
objs = Book.objects.filter(owner_id=auth.id)
for u in objs:
data = []
data.append(u.name)
data.append(auth.name)
data.append(u.translator)
data.append(u.press)
data.append(u.serializer)
data.append(u.page)
sheet.append(data)
return ExcelBookResponse(book, filename)
使用xlwt写入数据:
book = xlwt.Workbook()
auths = Auth.objects.filter(owner_id=1)
filename = '导出数据'
for auth in auths:
sheet = book.add_sheet(sensor.name)
sheet.write(0, 0, _("书名"))
sheet.write(0, 1, _("作者"))
sheet.write(0, 2, _("译者"))
sheet.write(0, 3, _("出版社"))
sheet.write(0, 4, _("序列号"))
sheet.write(0, 5, _("总页数"))
i = 1
objs = None
objs = Book.objects.filter(owner_id=auth.id)
for u in objs:
sheet.write(i, 0, u.name)
sheet.write(i, 1, auth.name)
sheet.write(i ,2,u.translator)
sheet.write(i ,3,u.press)
sheet.write(i, 4, u.serializer)
sheet.write(i, 5, u.page)
i += 1
return ExcelBookResponse(book, filename)
使用XlsxWriter写入数据:
book = xlsxwriter.Workbook(output)
auths = Auth.objects.filter(owner_id=1)
for auth in auths:
sheet = book.add_worksheet(sensor.name)
header = [
_("书名"),
_("作者"),
_("译者"),
_("出版社"),
_("序列号"),
_("总页数"),
]
sheet.write_row("A1", header)
objs = Book.objects.filter(owner_id=auth.id)
i = 1
for u in objs:
sheet.write(i, 0, u.name)
sheet.write(i, 1, auth.name)
sheet.write(i ,2,u.translator)
sheet.write(i ,3,u.press)
sheet.write(i, 4, u.serializer)
sheet.write(i, 5, u.page)
i += 1
book.close()
file_ext = 'xlsx'
mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
# self['Content-Disposition'] = 'attachment; filename*=UTF-8\'\'"{2}.{1}"; filename="{0}.{1}"'.format(filename.replace('"', '\"'), file_ext, urllib.parse.quote(filename.replace('"', '\"'))).encode('utf8')
return HttpResponse(content=output.getvalue(), content_type=mimetype)
三者的时间比较(两种方式的文件内容是一样的):
openpyxl: 文件大小为110.75kb, 平均时间大约为570ms
xlwt: 文件大小为505.91kb,平均时间大约为440ms
XlsxWrite: 文件大小为109.28kb,平均时间大约为500ms
xlwt写入的行数有限制,因此对于较大的文件来说,XlsxWrite的速度较快一点