feiyu02
2024-02-02 83455446544f89b0663a3f520744331ad8259289
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package com.flightfeather.uav.common.utils
 
import com.flightfeather.uav.common.exception.ResponseErrorException
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.util.CellRangeAddress
import org.apache.poi.xssf.streaming.SXSSFWorkbook
import org.apache.poi.xssf.usermodel.XSSFRow
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.jetbrains.kotlin.incremental.isJavaFile
import java.io.ByteArrayInputStream
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.time.LocalDate
import java.util.*
import kotlin.math.max
 
/**
 * @author riku
 * Date: 2020/6/12
 */
object ExcelUtil {
 
    private const val isLog = false
 
    class MyCell(
        var text: String,
        var rowSpan: Int = 1,
        var colSpan: Int = 1,
        var fontColor: Short? = null,
    )
 
    /**
     * 读取文件
     * @param file 要读取的文件
     * @param headerCheck 文件首行检查回调
     * @param onRow 单行内容回调,从第二行开始
     */
    fun read(file: File, headerCheck: (header: XSSFRow) -> Boolean, onRow: (row: Row) -> Unit): Boolean {
        if (!file.exists() || !file.isFile) throw ResponseErrorException("it's not a normal file!")
        if (!file.extension.equals("xls", ignoreCase = true) || !file.extension.equals("xlsx", ignoreCase = true)) {
            throw ResponseErrorException("file's extension name should be xls or xlsx!")
        }
        return read(FileInputStream(file), headerCheck, onRow)
    }
 
    fun read(input: InputStream, headerCheck: (header: XSSFRow) -> Boolean, onRow: (row: Row) -> Unit): Boolean {
        val workbook = XSSFWorkbook(input)
        val sheet1 = workbook.getSheetAt(0)
        val header = sheet1.getRow(sheet1.topRow.toInt())
        return if (headerCheck(header)) {
            // 获取迭代器并去除第一行标题
            val iterator = sheet1.rowIterator().also { it.next() }
            iterator.forEach { onRow(it) }
            true
        } else {
            false
        }
    }
 
    /**
     * 自动处理行合并数据
     */
    fun write2(heads: List<String>, contents: List<Array<Any>>, workbook: SXSSFWorkbook, sheetName: String) {
 
        val sheet = workbook.createSheet(sheetName)
 
        var rowIndex = 0
 
        if (heads.isNotEmpty()) {
            val rows = sheet.createRow(rowIndex)
            for (i in 0 until heads.size) {
                rows.createCell(i).setCellValue(heads[i])
            }
            rowIndex++
        }
 
        contents.forEach {
            val maxRow = getMaxRows(it)
 
            var rows = sheet.getRow(rowIndex) ?: sheet.createRow(rowIndex)
 
            val arrayMap = mutableMapOf<Int, Array<*>>()
 
            for (i in it.indices) {
                val cell = it[i]
 
                var rowspan = maxRow//合并的行的跨度
 
                val c =
                    if (cell is Array<*>) {
                        //当数据为数组时,需要根据最大行数重新计算该单元格的行跨度
                        arrayMap[i] = cell
                        rowspan = maxRow / if (cell.size == 0) 1 else cell.size
                        val c = cell[0]
                        if (c is MyCell) {
                            rowspan = c.rowSpan
                        }
                        if (rowspan > 1) {
                            log("合并1-1:$rowIndex;${rowIndex + rowspan - 1};$i")
                            sheet.addMergedRegion(CellRangeAddress(rowIndex, rowIndex + rowspan - 1, i, i))
                        }
                        if (cell.isEmpty()) {
                            ""
                        } else {
                            cell[0]
                        }
                    } else {
                        //当数据不是数组时,需要按最大行数合并单元格
                        if (rowspan > 1) {
                            log("合并1-2:$rowIndex;${rowIndex + rowspan - 1};$i")
                            sheet.addMergedRegion(CellRangeAddress(rowIndex, rowIndex + rowspan - 1, i, i))
                        }
                        cell
                    }
                when (c) {
                    is MyCell -> {
                        rows.createCell(i).setCellValue(c.text)
                        log("write1-1: ${c.text};($rowIndex, ${i})")
                    }
                    is String -> {
                        rows.createCell(i).setCellValue(c)
                        log("write1-2: ${c};($rowIndex, ${i})")
                    }
                    is Double -> rows.createCell(i).setCellValue(c)
                    is Boolean -> rows.createCell(i).setCellValue(c)
                    is Date -> rows.createCell(i).setCellValue(c)
                    is Calendar -> rows.createCell(i).setCellValue(c)
                    is LocalDate -> rows.createCell(i).setCellValue(c)
                }
            }
 
            for (i in 1 until maxRow) {
                rowIndex++
                arrayMap.forEach { map ->
                    rows = sheet.getRow(rowIndex) ?: sheet.createRow(rowIndex)
                    val array = map.value
                    if (i < array.size) {
//                        var rowspan = maxRow / array.size
                        var lastRowSpan = 1
                        var rowspan = 1
                        val c = array[i]
                        if (c is MyCell) {
                            rowspan = c.rowSpan
                        }
                        val _c = array[i - 1]
                        if (_c is MyCell) {
                            lastRowSpan = _c.rowSpan
                        }
                        var _rowIndex = rowIndex
                        var index = rowIndex
                        if (lastRowSpan > 1) {
                            index = rowIndex + (i * lastRowSpan) - 1
                            _rowIndex = index
                            rows = sheet.getRow(_rowIndex) ?: sheet.createRow(_rowIndex)
                        }
                        if (rowspan > 1) {
                            log("合并2:${index};${index + rowspan - 1};$i")
                            sheet.addMergedRegion(CellRangeAddress(index, index + rowspan - 1, i, i))
                        }
 
                        when (c) {
                            is MyCell -> {
                                rows.createCell(map.key).setCellValue(c.text)
                                log("write2-1: ${c.text};($_rowIndex, ${map.key})")
                            }
                            is String -> {
                                rows.createCell(map.key).setCellValue(c)
                                log("write2-2: ${c};($_rowIndex, ${map.key})")
                            }
                            is Double -> rows.createCell(map.key).setCellValue(c)
                            is Boolean -> rows.createCell(map.key).setCellValue(c)
                            is Date -> rows.createCell(map.key).setCellValue(c)
                            is Calendar -> rows.createCell(map.key).setCellValue(c)
                            is LocalDate -> rows.createCell(map.key).setCellValue(c)
                        }
                    }
                }
            }
 
            rowIndex++
        }
//        workbook.write(out)
//        workbook.close()
//        out.flush()
//        out.close()
    }
 
    /**
     * 自动处理行合并数据
     */
    fun write(
        heads: List<Array<String>>,
        contents: List<Array<Any>>,
        workbook: SXSSFWorkbook,
        sheetName: String = "sheet1",
        row: Int = 0,
    ): Int {
 
        val sheet = workbook.getSheet(sheetName) ?: workbook.createSheet(sheetName)
//        println("sheet: $sheetName")
 
        var rowIndex = row
 
        heads.forEach {
            val rows = sheet.createRow(rowIndex)
            for (i in it.indices) {
                rows.createCell(i).setCellValue(it[i])
            }
            rowIndex++
        }
 
        contents.forEach {
            val maxRow = getMaxRows(it)
 
            var rows = sheet.getRow(rowIndex) ?: sheet.createRow(rowIndex)
 
            val arrayMap = mutableMapOf<Int, Array<*>>()
 
            //列序号
            var col = 0
            for (i in it.indices) {
                val cell = it[i]
 
                var rowspan = maxRow//合并的行的跨度
                var colSpan = 1
 
                val c =
                    if (cell is Array<*>) {
                        //当数据为数组时,需要根据最大行数重新计算该单元格的行跨度
                        arrayMap[col] = cell
                        rowspan = maxRow / if (cell.size == 0) 1 else cell.size
                        val c = cell[0]
                        if (c is MyCell) {
                            rowspan = c.rowSpan
                            colSpan = c.colSpan
                        }
                        if (rowspan > 1 || colSpan > 1) {
                            log("合并1-1:$rowIndex;${rowIndex + rowspan - 1};$col")
                            sheet.addMergedRegion(CellRangeAddress(rowIndex,
                                rowIndex + rowspan - 1,
                                col,
                                col + colSpan - 1))
                        }
                        if (cell.isEmpty()) {
                            ""
                        } else {
                            cell[0]
                        }
                    } else {
                        //当数据不是数组时,根据设置合并
                        if (cell is MyCell) {
                            rowspan = cell.rowSpan
                            colSpan = cell.colSpan
                        }
                        if (rowspan > 1 || colSpan > 1) {
                            log("合并1-2:$rowIndex;${rowIndex + rowspan - 1};$col")
                            sheet.addMergedRegion(CellRangeAddress(rowIndex,
                                rowIndex + rowspan - 1,
                                col,
                                col + colSpan - 1))
                        }
                        cell
                    }
                when (c) {
                    is MyCell -> {
                        rows.createCell(col).apply {
                            c.fontColor?.let { fC ->
                                val font = workbook.createFont()
                                val cellStyle = workbook.createCellStyle()
 
                                font.color = fC
                                cellStyle.setFont(font)
                                setCellStyle(cellStyle)
                            }
                            setCellValue(c.text)
                        }
                        log("write1-1: ${c.text};($rowIndex, ${col})")
                    }
                    is String -> {
                        rows.createCell(col).setCellValue(c)
                        log("write1-2: ${c};($rowIndex, ${col})")
                    }
                    is Double -> rows.createCell(col).setCellValue(c)
                    is Int -> rows.createCell(col).setCellValue(c.toDouble())
                    is Boolean -> rows.createCell(col).setCellValue(c)
                    is Date -> rows.createCell(col).setCellValue(c)
                    is Calendar -> rows.createCell(col).setCellValue(c)
                    is LocalDate -> rows.createCell(col).setCellValue(c)
                }
 
                col += colSpan
            }
 
            for (i in 1 until maxRow) {
                rowIndex++
                arrayMap.forEach { map ->
                    rows = sheet.getRow(rowIndex) ?: sheet.createRow(rowIndex)
                    val array = map.value
                    if (i < array.size) {
//                        var rowspan = maxRow / array.size
                        var lastRowSpan = 1
                        var rowspan = 1
                        var colSpan = 1
                        val c = array[i]
                        if (c is MyCell) {
                            rowspan = c.rowSpan
                            colSpan = c.colSpan
                        }
                        val _c = array[i - 1]
                        if (_c is MyCell) {
                            lastRowSpan = _c.rowSpan
                        }
                        var _rowIndex = rowIndex
                        var index = rowIndex
                        if (lastRowSpan > 1) {
                            index = rowIndex + (i * lastRowSpan) - 1
                            _rowIndex = index
                            rows = sheet.getRow(_rowIndex) ?: sheet.createRow(_rowIndex)
                        }
                        if (rowspan > 1 || colSpan > 1) {
                            log("合并2:${index};${index + rowspan - 1};${map.key}")
                            sheet.addMergedRegion(CellRangeAddress(index,
                                index + rowspan - 1,
                                map.key,
                                map.key + colSpan - 1))
                        }
 
                        when (c) {
                            is MyCell -> {
                                rows.createCell(map.key).setCellValue(c.text)
                                log("write2-1: ${c.text};($_rowIndex, ${map.key})")
                            }
                            is String -> {
                                rows.createCell(map.key).setCellValue(c)
                                log("write2-2: ${c};($_rowIndex, ${map.key})")
                            }
                            is Double -> rows.createCell(map.key).setCellValue(c)
                            is Boolean -> rows.createCell(map.key).setCellValue(c)
                            is Date -> rows.createCell(map.key).setCellValue(c)
                            is Calendar -> rows.createCell(map.key).setCellValue(c)
                            is LocalDate -> rows.createCell(map.key).setCellValue(c)
                        }
                    }
                }
            }
 
            rowIndex++
        }
//        workbook.write(out)
//        workbook.close()
//        out.flush()
//        out.close()
        return rowIndex
    }
 
    private fun getMaxRows(rowArray: Array<Any>): Int {
        var maxRows = 1
        rowArray.forEach {
            if (it is Array<*>) {
                maxRows = max(it.size, maxRows)
            }
        }
        return maxRows
    }
 
    private fun log(log: String) {
        if (isLog) {
            println(log)
        }
    }
}