package cn.flightfeather.supervision.business.report
|
|
import cn.flightfeather.supervision.common.exception.BizException
|
import cn.flightfeather.supervision.common.utils.ExcelUtil
|
import org.apache.poi.hssf.usermodel.HSSFWorkbook
|
import java.io.FileOutputStream
|
import java.io.OutputStream
|
import java.util.*
|
|
/**
|
* excel报告模板基类
|
* 多个数据源
|
*/
|
// FIXME: 2022/7/15 模板简化:只有表头会涉及单元格合并,默认表内容中没有合并
|
abstract class BaseTemplateMulti(private val dataSourceList: List<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() {
|
if (dataSourceList.isEmpty()) throw BizException("${templateName}: 数据源为空")
|
//合成表头
|
cols.forEach {
|
it.combineHead(head, dataSourceList[0])
|
}
|
|
var i = 0
|
dataSourceList.forEach { dataSource ->
|
//数据源重置
|
dataSource.reset()
|
|
//合成数据
|
dataSource.loop { _, rowData ->
|
cols.forEach { col ->
|
val r = col.getOneRow(rowData)
|
if (i >= contents.size) {
|
contents.add(mutableListOf())
|
}
|
contents[i].addAll(r)
|
}
|
i++
|
}
|
}
|
}
|
|
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 fileName = "${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()) }
|
if (c.isNotEmpty() && c[0].isNotEmpty()) {
|
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)
|
}
|
|
fun toTableRows(): Pair<MutableList<Array<Any>>, MutableList<Array<Any>>> {
|
val h = mutableListOf<Array<Any>>()
|
val c = mutableListOf<Array<Any>>()
|
head.forEach { d ->
|
val tempH = mutableListOf<Any>()
|
d.forEach {
|
tempH.add(it.text)
|
}
|
h.add(tempH.toTypedArray())
|
}
|
contents.forEach {
|
c.add(it.toTypedArray())
|
}
|
if (c.isNotEmpty() && c[0].isNotEmpty()) {
|
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)
|
}
|
}
|