python 数据生成excel导出(xlwt,wlsxwrite)代码实例

yipeiwu_com6年前Python基础

这篇文章主要介绍了python 数据生成excel导出(xlwt,wlsxwrite)代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

话不多说,看代码:

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("无数据")

上边我也是盗的,只不过当时有需求,数据量大只能用xlsxwriter,然后下边是我用xlsxwriter写的,边学边写,还请多多关照:

import xlsxwriter,StringIO
    output = StringIO.StringIO()
    workbook = Workbook(output)
    if id:
      sheet_name = _(u"vvv")
      w = workbook.add_worksheet(sheet_name)
    else:
      sheet_name = _(u"vvvvvvv")
      w = workbook.add_worksheet(sheet_name)
""" 表格单元格样式"""
    head_cell_xf = workbook.add_format({
      'font_name': 'SimSun',
      'bold': True,
      'text_wrap': True,
      'valign': 'vcenter',
      'align': 'left',

      'bg_color': 'gray',
      'pattern': 1,
      'bottom': 1,
      'left': 1,
      'right': 1,
      'top': 1,
    })
    body_cell_xf = workbook.add_format({
      'font_name': 'SimSun',
      'text_wrap': True,
      'valign': 'vcenter',
      'align': 'left',

      'bg_color': 'gray',
      'pattern': 1,
      'bottom': 1,
      'left': 1,
      'right': 1,
      'top': 1,
    })

    w.write(0, 0, 'xxxx', head_cell_xf)
    w.write(0, 1, u'xxxx', head_cell_xf)
    w.set_column(1, 0, 18)
    w.set_column(1, 1, 100)
    excel_row = 1
    # cve_id = set()
    # i18n_name = set()
    data={}
    if id:
      res = xx.objects.get(id=id)
      res = res.vuls.split(';')
      for re in res:
        re = xx.objects.get(pk=xx)
        data[re.cve_id]=re.i18n_name[1]
        # w.write(excel_row, 0, re.cve_id,body_cell_xf)
        # w.write(excel_row, 1, re.i18n_name[1], body_cell_xf)
        # cve_id.add(re.cve_id)
        # cve_id.add(re.i18n_name[1])
        excel_row += 1
        progress_status = excel_row*100/len(res) # 获取进度

    else:
      res = xx.objects.get(pk=xx)
      res = res.white_list.split(',')
      for re in res:
        re = Vuln.objects.get(vul_id=re)
        data[re.cve_id] = re.i18n_name[1]
      
        excel_row += 1
        progress_status = excel_row * 100 / len(res)  # 获取进度
    w.write_column('A2', data.keys(), body_cell_xf)
    w.write_column('B2', data.values(), body_cell_xf)
    workbook.close()
    response = HttpResponse(output.getvalue(),
                content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment;filename=%s.xlsx' % xxx
    response.write(output.getvalue())
    progress_status = 0
    return response

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

在Python中利用Into包整洁地进行数据迁移的教程

在Python中利用Into包整洁地进行数据迁移的教程

动机 我们花费大量的时间将数据从普通的交换格式(比如CSV),迁移到像数组、数据库或者二进制存储等高效的计算格式。更糟糕的是,许多人没有将数据迁移到高效的格式,因为他们不知道怎么(或者不...

pygame游戏之旅 添加游戏介绍

pygame游戏之旅 添加游戏介绍

本文为大家分享了pygame游戏之旅的第9篇,供大家参考,具体内容如下 在游戏开始之前定义一个函数,用来显示游戏介绍: def game_intro(): intro = Tru...

matplotlib设置legend图例代码示例

matplotlib设置legend图例代码示例

本文主要是关于matplotlib的一些基本用法。 Demo import matplotlib.pyplot as plt import numpy as np # 绘制普通图像...

python批量修改图片大小的方法

本文实例为大家分享了python批量修改图片大小的具体代码,供大家参考,具体内容如下 引用的模块 from PIL import Image Image的使用 def res...

dataframe 按条件替换某一列中的值方法

如下所示: import pandas as pd content = ['T', 'F'] * 10 data = pd.DataFrame(content, columns=...