一、代码

备注:封装好了(可直接调用)

"""
-*- coding:utf-8 -*-
@Time   :2020/8/20 21:02
@Author :Jarvis
@File   :jar_excel_util.py
@Version:1.0
"""
from typing import List

import xlwt


class JarExcelUtil:
    def __init__(self, header_list: List[list]):
        """
        :param header_list: 如下格式
            例1:默认列宽
            header_list = [
                ['序号'],    # 表格第0列[此列表头名称]
                ['姓名'],
                ['性别'],
                ['爱好'],
                ['生日']
            ]
            例2:自定义列宽(列宽值为int类型 英文字符长度 如:10 表示列宽为10个英文字符长度)
            header = [
                ['序号', 5],  # 表格第0列[此列表头名称,列宽]
                ['姓名', 10], # 表格第1列[此列表头名称,列宽]
                ['性别', 10],
                ['爱好', 10],
                ['生日', 20]
            ]
        """
        self.data = header_list

    def write(self, out_file, data_body: List[list], sheet_name='sheet'):
        """
        写入数据
        :param out_file: 保存文件(如:test.xlsx)
        :param data_body: data_body[0]为表格第0行数据  data_body[0][0]为表格第0行第0列单元格值
        :param sheet_name:
        """
        # step1 判断数据正确性(每行列数是否与表头相同)
        count = 0
        for pro in data_body:
            if len(pro) != len(self.data):
                raise Exception(
                    'data_body数据错误 第{}行(从0开始) 需为{}个元素 当前行{}个元素:{}'.format(count, len(self.data), len(pro), str(pro)))
            count += 1

        # step2 写入数据
        wd = xlwt.Workbook()
        sheet = wd.add_sheet(sheet_name)

        # 表头
        for col in self.data:
            # 默认列宽
            if len(col) == 1:
                sheet.write(0, self.data.index(col), str(col[0]))
            # 自定义列宽
            if len(col) == 2:
                sheet.write(0, self.data.index(col), str(col[0]))
                # 设置列宽
                sheet.col(self.data.index(col)).width = 256 * col[1]  # 15个英文字符
        # 表体
        index = 1
        for pro in data_body:
            for d in self.data:
                value = pro[self.data.index(d)]
                # 若值类型是int、float 直接写入 反之 转成字符串写入
                if type(value) == int or type(value) == float:
                    sheet.write(index, self.data.index(d), value)
                else:
                    sheet.write(index, self.data.index(d), str(value))
            index += 1
        wd.save(out_file)


if __name__ == '__main__':
    header = [
        ['序号', 5],
        ['姓名', 10],
        ['性别', 10],
        ['爱好', 10],
        ['生日', 20]
    ]

    # header = [
    #     ['序号'],
    #     ['姓名'],
    #     ['性别'],
    #     ['爱好'],
    #     ['生日']
    # ]

    body = [
        [1, '张三', '', '篮球', '1994-07-23'],
        [2, '李四', '', '足球', '1994-04-03'],
        [3, '王五', '', '兵乓球', '1994-09-13']
    ]

    JarExcelUtil(header_list=header).write(out_file='测试.xlsx', data_body=body)

 

 

二、效果

生成的Excel

 

 

三、常用操作

3.1、设置行高

# 行高(第0行)
sheet.row(0).height_mismatch = True
sheet.row(0).height = 20 * 20  # 20为基数 * 20榜

3.2、设置列宽

# 列宽(第0列)
sheet.col(0).width = 256 * 30  # 256为基数 * 30个英文字符(约)

3.3、冻结(列与行)

# 冻结(列与行)
sheet.set_panes_frozen('1')
sheet.set_horz_split_pos(2)  # 冻结前2行
sheet.set_vert_split_pos(3)  # 冻结前3列
        
# 冻结首行
sheet.set_panes_frozen('1')
sheet.set_horz_split_pos(1)  # 冻结前1行(即首行)

3.4、设置单元格对齐方式

# 设置对齐方式
style_1 = xlwt.XFStyle()
al_1 = xlwt.Alignment()
al_1.horz = xlwt.Alignment.HORZ_CENTER  # 水平居中
al_1.vert = xlwt.Alignment.VERT_CENTER  # 垂直居中
style_1.alignment = al_1
sheet.write(0, 0, '第0行第0列单元格值', style_1)

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/danhuai/p/13538291.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!