django excel 导出

本文章导出的为 列表格式的数据
比如 [{‘a’:’a1’},{‘a’:’a2’},{‘a’:’a3’},{‘a’:’a4’}]
其实就是json的导出

import xlwt

def excel_data_export(data,
                      #name='exelname.xls',文件命名
                      path='exportedFile/',#文件保存位置
                      ):
    _data = data
    _path = path
    workbook = xlwt.Workbook(encoding='utf-8')
    if _data:
        booksheet = workbook.add_sheet('Sheet 1', cell_overwrite_ok=True)
        for i, row in enumerate(_data):
        #关于enumerate 下面有演示
            for j, col in enumerate(row):
                if i == 0:
                    booksheet.write(i, j, col)
                booksheet.write(i + 1, j, row[col])
        try:
            workbook.save('export.xls')
            return True

        except Exception as e:
            return e
    else:
        return None

如果想要导出中文字段名 可以通过修改json/dict 的key来显示

#比如有个json userinfo
for i in userinfo:
    i['用户名'] = i.pop('username') 
    #username 为原json 中的英文字段
    #用户名 为 修改后显示的中文字段
    #pop 实际在这里操作了俩个步骤 替换key ,删除 原key的键值对
excel_data_export(userinfo)
    #这里就直接可以导出了
关于enumerate
python的内置模块
例:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, ]
for x, y in enumerate(a):
    print(x,y)

结果:
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

猜你喜欢

转载自blog.csdn.net/qq_33042187/article/details/78727296
今日推荐