python各種excel寫入方式速度比較

經過實驗,新建一個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的速度較快一點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章