Python写入excel

写入excel的代码片段

# coding: utf-8
import xlwt

workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet("分发记录")

# ----------------- 表头列表样式 ------------------
style = xlwt.XFStyle()  # 头部样式对象

borders = xlwt.Borders()  # 边框对象
borders.left = xlwt.Borders.THICK
borders.right = xlwt.Borders.THICK
borders.top = xlwt.Borders.THICK
borders.bottom = xlwt.Borders.THICK

style.borders = borders
# -----------------------------------------------

# ----------------------- 数据的列表样式 -----------
styleBody = xlwt.XFStyle()  # body样式对象

borders = xlwt.Borders()  # 边框对象
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN

styleBody.borders = borders
# -----------------------------------------------

outputHeader = ['a', 'b', 'c']  # 表头

# excel 动态表头
for order, each_header in enumerate(outputHeader):
    worksheet.write(0, order, each_header, style)
    worksheet.col(order).width = 5000  # 列宽

records = [
    {
        'a': 1,
        'b': 2,
        'c': 3
    },
    {
        'a': 11,
        'b': 22,
        'c': 33
    },

]  # 列表嵌套的数据字典
# 写入数据部分
for index, eachrecord in enumerate(records, start=1):
    for dataOrder, data in eachrecord.items():
        worksheet.write(index, outputHeader.index(dataOrder), data, styleBody)
workbook.save('test.xlsx')


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页