封装xlwt导出excel

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

xlwt使用Python语言开发的写入Excel文件的拓展工具,相应的有xlrd拓展包,专门用于excel读取。可以实现指定表单、指定单元格写入。支持excel03版到excel2013班,使用时请确定已经安装python环境。

1. export_test.py

# -*- coding: utf-8 -*-

from famiover.model.model import Model
from famiover.util.excelsheet import ExcelSheet
from famiover.util.excelutil import ExcelUtil

if __name__ == "__main__":
    eu = ExcelUtil('filename.xls')
    # 模拟数据库得到数据,这里同样可以是list类型
    dicts = {
        'r1': {'name': 'famiover', 'age': 25},
        'r2': {'name': 'famiover', 'age': 25}
    }
    model_key = 'teacher'
    excelsheet1 = ExcelSheet(eu, 'sheet_name', dicts, Model, model_key)
    excelsheet2 = ExcelSheet(eu, 'sheet_name', dicts, Model, model_key)
    excelsheet3 = ExcelSheet(eu, 'sheet_name', dicts, Model, model_key)
    excelsheet4 = ExcelSheet(eu, 'sheet_name', dicts, Model, model_key)
    # 保存至excel
    eu.excelutil_save()

2.ExcelSheet.py
# -*- coding: utf-8 -*-
from famiover.util.object_util import is_dict


class ExcelSheet(object):
    def __init__(self, excelutil, sheet_name, db_result, class_name, model_key):
        """初始化sheet对象"""

        # 创建sheet对象
        self.sheet = excelutil.wbk.add_sheet(sheet_name, cell_overwrite_ok=True)
        # 设置sheet的内容
        self.sheet_set_content(excelutil, db_result, class_name, model_key)

    def sheet_set_content(self, excelutil, db_result, class_name, model_key):
        """设置excel内容"""

        '''
        db_result一般为迭代类型,有时候重组为字典类型。不需要重组时就是迭代类型
        '''

        if is_dict(db_result):
            result = excelutil.excel_dicts_models(db_result, class_name)
        else:
            result = excelutil.excel_iterable_models(db_result, class_name)
        if len(result) < 1:
            return
        # 取第一个作为转化的目标类型
        model = result[0]
        self.sheet_set_row_name(model, model_key)
        self.sheet_set_data(result, model_key)

    def sheet_set_row_name(self, model, model_key):
        """设置excel的列名"""

        desc = model.get_desc(model_key)
        row = 0
        for key, value in desc.items():
            self.sheet.write(0, row, value)
            row += 1

    def sheet_set_data(self, result, model_key):
        """设置excel的数据"""

        for row, m in enumerate(result):
            column = 0
            for key, value in m.get_desc(model_key).items():
                self.sheet.write(row + 1, column, getattr(m, key))
                column += 1

3. ExcelUtil.py
# -*- coding: utf-8 -*-
import xlwt


class ExcelUtil(object):
    def __init__(self, filename):
        """初始化sheet对象"""
        self.wbk = xlwt.Workbook(encoding="utf-8", style_compression=0)
        self.filename = filename

    def excelutil_save(self):
        """保存到excel文件"""
        if not (self.filename.endswith(".xlsx") or self.filename.endswith(".xls")):
            self.filename += ".xls"
        self.wbk.save(self.filename)

    def excel_dicts_models(self, db_result, model):
        """将字典{key:{},key:{}}转为对象"""
        """dicts是一种字典包含字典"""
        result = []
        for key, value in db_result.items():
            result.append(self.excel_dict_model(value, model))
        return result

    def excel_iterable_models(self, db_result, model):
        """将列表[{},{}]转为对象"""
        """list是一种集合包含字典"""
        result = []
        for value in db_result:
            result.append(self.excel_dict_model(value, model))
        return result

    @staticmethod
    def excel_dict_model(dic, model):
        """将字典转为对象"""
        m = model()  # 根据类名直接创建对象
        for key, value in dic.items():
            setattr(m, key, value)
        return m

4. model.py
# -*- coding: utf-8 -*-
from collections import OrderedDict


class Model(object):
    def __init__(self):
        self.desc = OrderedDict()

    def get_desc(self, model_key):

        if model_key == 'famiover':
            self.desc['name'] = '姓名'
            self.desc['age'] = '年龄'
            return self.desc

转载于:https://my.oschina.net/famiover/blog/761764

你可能感兴趣的:(封装xlwt导出excel)