Home  >  Article  >  Backend Development  >  Example of python exporting data to excel

Example of python exporting data to excel

不言
不言Original
2018-05-03 11:54:079673browse

This article mainly introduces the example of exporting data to excel in python. It has certain reference value. Now I share it with you. Friends in need can refer to it.

This article is under the django framework. To write and obtain data from the database, django-orm

is used to export data to excel using python. It is so simple! (Ordinary excel format)

Install xlwt

##

pip install xlwt

Write py file

from xlwt import *
import StringIO
from apps.song.models import Song
def excel_ktvsong(request):

  """
导出excel表格
"""

  _id = request.GET.get('id', 0)

  list_obj = Song.objects.filter(is_delete__exact=False)
 # django orm  
  if list_obj:
 # 创建工作薄

    ws = Workbook(encoding='utf-8')

    w = ws.add_sheet(u"歌曲列表")

    w.write(0, 0, u"歌曲名称")

    w.write(0, 1, u"歌手")

    # 写入数据

    excel_row = 1

    for obj in list_obj:

      data_song = obj.song

      data_singer_name = obj.singer_name

      w.write(excel_row, 0, data_song)

      w.write(excel_row, 1, data_singer_name)


      excel_row += 1


    sio = StringIO.StringIO()

    ws.save(sio)

    sio.seek(0)

    response = HttpResponse(sio.getvalue(),     
    content_type='application/vnd.ms-excel')

    response['Content-Disposition'] = 'attachment;filename=%s.xls' % time.strftime('%Y%m%d%H%M%S')

    response.write(sio.getvalue())

    return response

  else:

    return HttpResponse("无数据")

Related recommendations:


Use python to implement data analysis

Detailed explanation of Python implementation of database programming method

The above is the detailed content of Example of python exporting data to excel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn