feiyu02
2025-09-12 dc4f12f66685260ac357997680e5f3fe723c3c4a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package cn.flightfeather.supervision.business.report
 
import cn.flightfeather.supervision.common.utils.Constant
import cn.flightfeather.supervision.common.utils.DateUtil
import cn.flightfeather.supervision.common.utils.ExcelUtil
import cn.flightfeather.supervision.domain.ds1.entity.Problemlist
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import tk.mybatis.mapper.entity.Example
import java.io.FileOutputStream
import java.io.OutputStream
import java.util.*
 
/**
 * excel报告模板基类
 * 单个数据源
 */
// FIXME: 2022/7/15 模板简化:只有表头会涉及单元格合并,默认表内容中没有合并
abstract class BaseTemplate(val dataSource: DataSource) : BaseOutputInterface {
 
    //列组合
    abstract val cols: List<BaseCols>
 
    //模板名称
    abstract val templateName: String
 
    //表头
    val head = mutableListOf<MutableList<ExcelUtil.MyCell>>()
 
    //内容
    val contents = mutableListOf<MutableList<Any>>()
 
 
    open fun execute() {
        //数据源重置
        dataSource.reset()
        //合成表头
        cols.forEach {
            it.combineHead(head, dataSource)
        }
        //合成数据
        dataSource.loop { index, rowData ->
            cols.forEach { col ->
                val r = col.getOneRow(rowData)
                if (index >= contents.size) {
                    contents.add(mutableListOf())
                }
                contents[index].addAll(r)
            }
        }
    }
 
    override fun toWorkBook(wb: HSSFWorkbook) {
        val f = tableFormat()
        ExcelUtil.write(f.first, f.second, wb, templateName)
    }
 
    override fun toOutputStream(out: OutputStream, sheetName: String?) {
        val f = tableFormat()
        ExcelUtil.write2(out, f.first, f.second, sheetName ?: templateName)
    }
 
    /**
     * 输出为文档
     */
    override fun toFile(path: String) {
        val fileName = "${dataSource.areaName()}-${templateName}-${Date().time}.xls"
        val out = FileOutputStream(path + fileName)
        toOutputStream(out)
    }
 
    /**
     * 表头和表内容格式转化
     */
    fun tableFormat(): Pair<MutableList<Array<Any>>, MutableList<Array<Any>>> {
        val h = mutableListOf<Array<Any>>()
        val c = mutableListOf<Array<Any>>()
        head.forEach { h.add(it.toTypedArray()) }
        contents.forEach { c.add(it.toTypedArray()) }
        val index = c[0][0]
        //按照第一列进行排序
        if (index is Int) {
            c.sortBy {
                if (it[0] is Int) {
                    it[0] as Int
                } else {
                    0
                }
            }
        } else {
            c.sortBy {
                it[0].toString()
            }
        }
        return Pair(h, c)
    }
}