-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathTemplateSheet.java
More file actions
1510 lines (1410 loc) · 58 KB
/
TemplateSheet.java
File metadata and controls
1510 lines (1410 loc) · 58 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2017-2023, guanquan.wang@hotmail.com All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ttzero.excel.entity;
import org.dom4j.Document;
import org.dom4j.Element;
import org.ttzero.excel.entity.e7.XMLWorksheetWriter;
import org.ttzero.excel.entity.style.Border;
import org.ttzero.excel.entity.style.ColorIndex;
import org.ttzero.excel.entity.style.Fill;
import org.ttzero.excel.entity.style.Font;
import org.ttzero.excel.entity.style.NumFmt;
import org.ttzero.excel.entity.style.Styles;
import org.ttzero.excel.manager.Const;
import org.ttzero.excel.reader.CrossDimension;
import org.ttzero.excel.util.FileUtil;
import org.ttzero.excel.util.SAXReaderUtil;
import org.ttzero.excel.validation.ListValidation;
import org.ttzero.excel.validation.Validation;
import org.ttzero.excel.reader.Cell;
import org.ttzero.excel.reader.CellType;
import org.ttzero.excel.reader.Col;
import org.ttzero.excel.reader.Dimension;
import org.ttzero.excel.reader.Drawings;
import org.ttzero.excel.reader.ExcelReader;
import org.ttzero.excel.reader.FullSheet;
import org.ttzero.excel.reader.RowSetIterator;
import org.ttzero.excel.util.DateUtil;
import org.ttzero.excel.util.StringUtil;
import java.beans.IntrospectionException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import static org.ttzero.excel.entity.IWorksheetWriter.isString;
import static org.ttzero.excel.entity.SimpleSheet.defaultDatetimeCell;
import static org.ttzero.excel.entity.style.Styles.INDEX_FONT;
import static org.ttzero.excel.util.ReflectUtil.listDeclaredFieldsUntilJavaPackage;
import static org.ttzero.excel.util.ReflectUtil.readMethodsMap;
/**
* 模板工作表,它支持指定一个已有的Excel文件作为模板导出,{@code TemplateSheet}将复制模板工作表的样式并替换占位符,
* 同时{@code TemplateSheet}也可以和其它{@code Worksheet}混用,这意味着可以添加多个模板工作表和普通工作表。
*
* <p>创建模板工作表需要指定模板文件,它可以是本地文件也可是输入流{@code InputStream},支持的类型包含{@code xls}
* 和{@code xlsx}两种格式,除模板文件外还需要指定工作表,未指定工作表时默认以第一个工作表做为模板。</p>
*
* <p>TemplateSheet工作表导出时不受ExcelColumn注解限制,导出的数据范围由模板中的占位符决定,
* 默认占位符由一对封闭的大括号{@code ${key}}组成,虽然占位符与EL表达式写法相似但模板占位符并不具备EL的能力,
* 所以无法使用{@code ${1 + 2}}或{@code ${System.getProperty("user.name")}}这类语句来做运算,
* 占位符<b>仅做替换不做运算</b>所以不需要担心安全漏洞问题。</p>
*
* <p>{@link #setData}方法为占位符绑定值,支持对象、Map、Array和List类型,数据量较大时也可以绑定一个数据生产者{@code data-supplier}来分片拉取数据,
* 它被定义为{@code BiFunction<Integer, T, List<T>>},其中第一个入参{@code Integer}表示已拉取数据的记录数
* (并非已写入数据),第二个入参{@code T}表示上一批数据中最后一个对象,业务端可以通过这两个参数来计算下一批数据应该从哪个节点开始拉取,
* 通常你可以使用第一个参数除以每批拉取的数据大小来确定当前页码,如果数据已排序则可以使用{@code T}对象的排序字段来计算下一批数据的游标以跳过
* {@code limit ... offset ... }分页查询从而极大提升取数性能。</p>
*
* <pre>
* new Workbook("模板测试")
* // 模板工作表
* .addSheet(new TemplateSheet(Paths.get("./template.xlsx"))
* // 免分页查询用户,根据ID排序并游标拉取
* .setData((i,lastOne) -> queryUser(i > 0 ? ((User)lastOne).getId():0))
* // 普通对象数组工作表
* .addSheet(new ListSheet<>().setData(list))
* .writeTo(Paths.get("/tmp/"));</pre>
*
* <p>每个占位符都有一个命名空间,使用${namespace.key}这种格式来添加命名空间,默认命名空间为{@code null}。
* 占位符中还包含三个内置函数它们分别为[@{@code link:}]、[@{@code list:}]和[@{@code media:}],
* 分别用于设置单元格的值为超链接、序列和图片,其中序列的值可以从源工作表中获取也可以使用{@link #setData(String, Object)}来设置。
* <b>注意:内置函数必须独占一个单元格且仅识别固定的三个内置函数,任意其它命令将被识别为普通命名空间</b></p>
*
* <p>占位符整体样式:[@内置函数:][命名空间][.]<占位符></p>
*
* <pre>
* template.xlsx模板如下:
* +--------+--------+--------------+---------------+------------------+
* | 姓名 | 年龄 | 性别 | 头像 | 简历原件 |
* +--------+--------+--------------+---------------+------------------+
* |${name} | ${age} | ${@list:sex} | ${@media:pic} | ${@link:jumpUrl} |
* +--------+--------+--------------+---------------+------------------+
*
* // 组装测试数据
* List<Map<String, Object>> data = new ArrayList<>();
* Map<String, Object> row1 = new HashMap<>();
* row1.put("name", "张三");
* row1.put("age", 26);
* row1.put("sex", "男");
* row1.put("pic", Paths.get("./images/head.png"));
* row1.put("jumpUrl", "{@code https://jianli.com/zhangsan}");
* data.add(row1);
*
* new Workbook("内置函数测试")
* // 模板工作表
* .addSheet(new TemplateSheet(Paths.get("./template.xlsx"))
* // 替换模板中占位符
* .setData(data)
* // 替换模板中"@list:sex"值为性别序列
* .setData("@list:sex", Arrays.asList("未知", "男", "女")))
* .writeTo(Paths.get("/tmp/"));</pre>
*
* <p>参考文档:</p>
* <p><a href="https://github.com/wangguanquan/eec/wiki/3-%E6%A8%A1%E6%9D%BF%E5%AF%BC%E5%87%BA">模板导出</a></p>
*
* @author guanquan.wang at 2023-12-01 15:10
*/
public class TemplateSheet extends Sheet {
/**
* 未实例化的列,可用于在写超出预知范围外的列
*/
protected static final Column UNALLOCATED_COLUMN = new Column();
/**
* 内置单元格类型-超链接样式
*/
public static final String HYPERLINK_KEY = "@link:";
/**
* 内置单元格类型-图片
*/
public static final String MEDIA_KEY = "@media:";
/**
* 内置单元格类型-序列
*/
public static final String LIST_KEY = "@list:";
/**
* 占位符前缀和后缀
*/
protected String prefix = "${", suffix = "}";
/**
* 模板路径
*/
protected Path templatePath;
/**
* 模板流
*/
protected InputStream templateStream;
/**
* 读取模板用
*/
protected ExcelReader reader;
/**
* 源工作表索引
*/
protected int originalSheetIndex;
/**
* 源工作表名
*/
protected String originalSheetName;
/**
* 行数据迭代器
*/
protected CommitRowSetIterator rowIterator;
/**
* 样式映射,缓存源样式索引映射到目标样式索引
*/
protected Map<Integer, Integer> styleMap;
/**
* 图片
*/
protected List<Drawings.Picture> pictures;
/**
* 以Excel格式输出
*/
protected boolean writeAsExcel,
/**
* 使用源工作表名称作为当前工作表名
*/
useOriginalSheetName;
/**
* 包含占位符的单元格预处理后的结果
*/
protected PreCell[][] preCells;
/**
* 占位符位置标记 pf: 当前占位符的行号 pi: 当前占位符在preNodes的下标
* afr:auto-filter row
*/
protected int pf, pi, afr = -1;
/**
* 合并单元格(输出时需特殊处理)
*/
protected List<Dimension> mergeCells;
/**
* 缓存源文件合并单元格
* Key: 首坐标 Value:单元格范围
*/
protected Map<Long, Dimension> mergeCells0;
/**
* 填充数据缓存
*/
protected Map<String, ValueWrapper> namespaceMapper = new HashMap<>();
/**
* 缓存源文件批注
* Key: 坐标 Value:批注
*/
protected Map<Long, Comment> comments0;
/**
* 缓存源文件数据验证
*/
protected List<Validation> validations0;
/**
* Delete the temp file if close buffer
*/
protected boolean shouldDelete;
/**
* 实例化模板工作表,默认以第一个工作表做为模板
*
* @param templatePath 模板路径
*/
public TemplateSheet(Path templatePath) {
this(templatePath, 0);
}
/**
* 实例化模板工作表,默认以第一个工作表做为模板
*
* @param name 指定工作表名称
* @param templatePath 模板路径
*/
public TemplateSheet(String name, Path templatePath) {
this(name, templatePath, 0);
}
/**
* 实例化模板工作表并指定模板工作表索引,如果指定索引超过模板Excel中包含的工作表数量则抛异常
*
* @param templatePath 模板路径
* @param originalSheetIndex 指定源工作表索引(从0开始)
*/
public TemplateSheet(Path templatePath, int originalSheetIndex) {
this(null, templatePath, originalSheetIndex);
}
/**
* 实例化模板工作表并指定模板工作表索引,如果指定索引超过模板Excel中包含的工作表数量则抛异常
*
* @param name 指定工作表名称
* @param templatePath 模板路径
* @param originalSheetIndex 指定源工作表索引(从0开始)
*/
public TemplateSheet(String name, Path templatePath, int originalSheetIndex) {
this.name = name;
this.templatePath = templatePath;
this.originalSheetIndex = originalSheetIndex;
}
/**
* 实例化模板工作表并指定模板工作表名,如果指定源工作表不存在则抛异常
*
* @param templatePath 模板路径
* @param originalSheetName 指定源工作表名
*/
public TemplateSheet(Path templatePath, String originalSheetName) {
this(null, templatePath, originalSheetName);
}
/**
* 实例化模板工作表并指定模板工作表名,如果指定源工作表不存在则抛异常
*
* @param name 指定工作表名称
* @param templatePath 模板路径
* @param originalSheetName 指定源工作表名
*/
public TemplateSheet(String name, Path templatePath, String originalSheetName) {
this.name = name;
this.templatePath = templatePath;
this.originalSheetName = originalSheetName;
}
/**
* 实例化模板工作表,默认以第一个工作表做为模板
*
* @param templateStream 模板输入流
*/
public TemplateSheet(InputStream templateStream) {
this(templateStream, 0);
}
/**
* 实例化模板工作表,默认以第一个工作表做为模板
*
* @param name 设置工作表名
* @param templateStream 模板输入流
*/
public TemplateSheet(String name, InputStream templateStream) {
this(name, templateStream, 0);
}
/**
* 实例化模板工作表并指定模板工作表索引,如果指定索引超过模板Excel中包含的工作表数量则抛异常
*
* @param templateStream 模板输入流
* @param originalSheetIndex 指定源工作表索引
*/
public TemplateSheet(InputStream templateStream, int originalSheetIndex) {
this(null, templateStream, originalSheetIndex);
}
/**
* 实例化模板工作表并指定模板工作表名,如果指定源工作表不存在则抛异常
*
* @param templateStream 模板输入流
* @param originalSheetName 指定源工作表名
*/
public TemplateSheet(InputStream templateStream, String originalSheetName) {
this(null, templateStream, originalSheetName);
}
/**
* 实例化模板工作表并指定模板工作表索引,如果指定索引超过模板Excel中包含的工作表数量则抛异常
*
* @param name 设置工作表名
* @param templateStream 模板输入流
* @param originalSheetIndex 指定源工作表索引
*/
public TemplateSheet(String name, InputStream templateStream, int originalSheetIndex) {
this.name = name;
this.templateStream = templateStream;
this.originalSheetIndex = originalSheetIndex;
}
/**
* 实例化模板工作表并指定模板工作表名,如果指定源工作表不存在则抛异常
*
* @param name 设置工作表名
* @param templateStream 模板输入流
* @param originalSheetName 指定源工作表名
*/
public TemplateSheet(String name, InputStream templateStream, String originalSheetName) {
this.name = name;
this.templateStream = templateStream;
this.originalSheetName = originalSheetName;
}
/**
* 设置占位符前缀,默认前缀为{@code $ģ}
*
* @param prefix 占位符前缀
* @return 当前工作表
*/
public TemplateSheet setPrefix(String prefix) {
if (StringUtil.isBlank(prefix))
throw new IllegalArgumentException("Illegal prefix value");
this.prefix = prefix;
return this;
}
/**
* 设置占位符后缀,默认后缀为{@code ĥ}
*
* @param suffix 占位符后缀
* @return 当前工作表
*/
public TemplateSheet setSuffix(String suffix) {
if (StringUtil.isBlank(suffix))
throw new IllegalArgumentException("Illegal suffix value");
this.suffix = suffix;
return this;
}
/**
* 使用源工作表名称作为当前工作表名
*
* @return 当前工作表
*/
public TemplateSheet useOriginalSheetName() {
this.useOriginalSheetName = true;
return this;
}
/**
* 绑定数据到默认命名空间,默认命名空间为{@code null}
*
* @param o 任意对象,可以为Java Bean,Map,或者数组
* @return 当前工作表
*/
public TemplateSheet setData(Object o) {
return setData(null, o);
}
/**
* 绑定数据到指定命名空间上
*
* @param namespace 命名空间
* @param o 任意对象,可以为Java Bean,Map,或者数组
* @return 当前工作表
*/
public TemplateSheet setData(String namespace, Object o) {
if ("this".equals(namespace)) namespace = null;
ValueWrapper vw = namespaceMapper.get(namespace);
if (vw == null) {
vw = new ValueWrapper();
namespaceMapper.put(namespace, vw);
} else LOGGER.warn("The namespace[{}] already exists.", namespace);
if (o == null) vw.option = 0;
else {
Class<?> clazz = o.getClass();
if (Map.class.isAssignableFrom(clazz)) {
vw.option = 2;
Map map = (Map) o;
if (vw.map == null) vw.map = map;
else vw.map.putAll(map);
}
else if (List.class.isAssignableFrom(clazz)) {
List list = (List) o;
Object oo = getFirstObject(list);
if (oo != null) {
vw.option = Map.class.isAssignableFrom(oo.getClass()) ? 3 : 4;
if (vw.list == null) vw.list = list; else vw.list.addAll(list);
if (vw.option == 4) vw.accessibleObjectMap = parseClass(oo.getClass());
} else vw.option = 0;
}
else if (clazz.isArray()) {
int len = Array.getLength(o);
if (vw.list == null) vw.list = new ArrayList<>(len);
for (int i = 0; i < len; i++) {
Object oo = Array.get(o, i);
vw.list.add(oo);
if (oo != null && vw.option == 0) {
vw.option = Map.class.isAssignableFrom(oo.getClass()) ? 3 : 4;
if (vw.option == 4) vw.accessibleObjectMap = parseClass(oo.getClass());
}
}
}
else {
vw.o = o;
vw.option = 1;
vw.accessibleObjectMap = parseClass(clazz);
}
}
return this;
}
/**
* 绑定一个{@code Supplier}到默认命名空间,适用于未知长度或数量最大的数组
*
* @param dataSupplier 数据产生者
* @return 当前工作表
*/
public TemplateSheet setData(BiFunction<Integer, Object, List<?>> dataSupplier) {
return setData(null, dataSupplier);
}
/**
* 绑定一个{@code Supplier}到指定命名空间,适用于未知长度或数量最大的数组
*
* @param namespace 命名空间
* @param dataSupplier 数据产生者
* @return 当前工作表
*/
public TemplateSheet setData(String namespace, BiFunction<Integer, Object, List<?>> dataSupplier) {
if ("this".equals(namespace)) namespace = null;
ValueWrapper vw = namespaceMapper.get(namespace);
if (vw != null) {
LOGGER.warn("The namespace[{}] already exists.", namespace);
} else {
vw = new ValueWrapper();
namespaceMapper.put(namespace, vw);
}
vw.supplier = dataSupplier;
// 加载第一批数据预处理数据类型
if (dataSupplier != null) {
List list = dataSupplier.apply(0, null);
Object oo = getFirstObject(list);
if (oo != null) {
vw.size += list.size();
if (vw.list == null) vw.list = list;
else vw.list.addAll(list);
vw.option = Map.class.isAssignableFrom(oo.getClass()) ? 3 : 4;
if (vw.option == 4) vw.accessibleObjectMap = parseClass(oo.getClass());
} else vw.option = 0;
}
return this;
}
/**
* 获取下一段{@link RowBlock}行块数据,工作表输出协议通过此方法循环获取行数据并落盘,
* 行块被设计为一个滑行窗口,下游输出协议只能获取一个窗口的数据默认包含32行。
*
* @return 行块
*/
public RowBlock nextBlock() {
rowBlock.clear();
// 装载数据(这里不需要判断是否有表头,模板不需要表头)
resetBlockData();
return rowBlock.flip();
}
@Override
public Column[] getAndSortHeaderColumns() {
if (!headerReady) {
// 解析模板工作表并复制信息到当前工作表中
int size;
try {
size = init();
} catch (IOException e) {
throw new ExcelWriteException(e);
}
if (size <= 0) columns = new Column[0];
else {
sortColumns(columns);
calculateRealColIndex();
resetCommonProperties(columns);
}
markExtProp();
headerReady = true;
}
return columns;
}
/**
* 读取模板头信息并复杂到当前工作表
*
* @return 列的个数
* @throws IOException 读取模板异常
*/
protected int init() throws IOException {
// 实例化ExcelReader
if (templateStream != null) {
templatePath = Files.createTempFile("eec-", null);
if (templatePath == null) throw new IOException("Create temp directory error. Please check your permission");
OutputStream os = Files.newOutputStream(templatePath);
FileUtil.cp(templateStream, os);
FileUtil.close(os);
FileUtil.close(templateStream);
templateStream = null;
shouldDelete = true;
}
if (templatePath != null) reader = ExcelReader.read(templatePath);
// 查找源工作表
org.ttzero.excel.reader.Sheet[] sheets = reader.all();
if (StringUtil.isNotBlank(originalSheetName)) {
int index = 0;
for (; index < sheets.length && !originalSheetName.equals(sheets[index].getName()); index++) ;
if (index >= sheets.length)
throw new IOException("The original worksheet [" + originalSheetName + "] does not exist in template file.");
originalSheetIndex = index;
} else if (originalSheetIndex < 0 || originalSheetIndex >= sheets.length)
throw new IOException("The original worksheet index [" + originalSheetIndex + "] is out of range in template file[0-" + sheets.length + "].");
// 加载模板工作表
FullSheet sheet = reader.sheet(originalSheetIndex).asFullSheet();
writeAsExcel = sheetWriter != null && XMLWorksheetWriter.class.isAssignableFrom(sheetWriter.getClass());
// 使用源工作表名称作为当前工作表名
if (useOriginalSheetName) setName(sheet.getName());
// 解析公共信息
int n = prepareCommonData(sheet);
// 预处理样式和占位符
rowIterator = prepare(sheet.reset());
pf = preCells == null ? -1 : preCells[0][0].row;
// 忽略表头输出
super.ignoreHeader();
// 解析公共信息
return n;
}
@Override
protected void resetBlockData() {
for (int rbs = rowBlock.capacity(), n = 0, limit = sheetWriter.getRowLimit(); n++ < rbs && rows < limit && rowIterator.hasNext(); ) {
Row row = rowBlock.next();
org.ttzero.excel.reader.Row row0 = rowIterator.next();
row.index = rows = rowIterator.rows - 1;
row.height = row0.getHeight();
row.hidden = row0.isHidden();
// 重置单行数据
resetRowData(row0, row);
}
}
/**
* 重置单行数据
*
* @param row0 源行
* @param row 目标行
*/
protected void resetRowData(org.ttzero.excel.reader.Row row0, Row row) {
Dimension mergeCell;
PreCell pn;
Comment comment;
// 空行特殊处理(lc-fc=-1)
int len = Math.max(row0.getLastColumnIndex(), 0);
Cell[] cells = row.realloc(len);
// 预处理
if (row0.getRowNum() == pf && !rowIterator.hasFillCell) rowIterator.withPreNodes(preCells[pi], namespaceMapper);
for (int i = 0; i < len; i++) {
Cell cell = cells[i], cell0 = row0.getCell(i);
// 复制样式
cell.xf = styleMap.getOrDefault(cell0.xf, 0);
if (cell.h) cell.xf = hyperlinkStyle(workbook.getStyles(), cell.xf);
boolean fillCell = false;
// 复制数据
switch (row0.getCellType(cell0)) {
case STRING:
if (rowIterator.hasFillCell && (pn = rowIterator.preNodes[i]) != null) {
fillCell = true;
fillValue(row, cell, pn, UNALLOCATED_COLUMN);
// 处理单行合并单元格
if (pn.m != null) {
// 正数为行合并 负数为列合并
if (pn.m > 0) mergeCells.add(new Dimension(rows + 1, (short) (i + 1), rows + 1, (short) (i + pn.m + 1)));
else mergeCells.add(new Dimension(rows + 1, (short) (i + 1), rows + ~pn.m, (short) (i + 1)));
}
} else cell.setString(row0.getString(cell0));
break;
// FIXME 范围外的数据不需要复制,要继续向后走
case LONG: cell.setLong(row0.getLong(cell0)); break;
case INTEGER: cell.setInt(row0.getInt(cell0)); break;
case DECIMAL: cell.setDecimal(row0.getDecimal(cell0)); break;
case DOUBLE: cell.setDouble(row0.getDouble(cell0)); break;
case DATE: cell.setDateTime(DateUtil.toDateTimeValue(row0.getTimestamp(cell0))); break;
case BOOLEAN: cell.setBool(row0.getBoolean(cell0)); break;
case BLANK: cell.emptyTag(); break;
default:
}
if (!writeAsExcel) continue;
// TODO 复制公式(不是简单的复制,需重新计算位置)
if (row0.hasFormula(cell0)) cell.setFormula(row0.getFormula(cell0));
long k = dimensionKey(row0.getRowNum() - 1, i);
// 合并单元格重新计算位置
if (!fillCell && mergeCells0 != null && (mergeCell = mergeCells0.get(k)) != null) {
int r = rows - row0.getRowNum() + 1;
mergeCells.add(new Dimension(mergeCell.firstRow + r, mergeCell.firstColumn, mergeCell.lastRow + r, mergeCell.lastColumn));
}
if (comments0 != null && (comment = comments0.get(k)) != null) {
createComments().addComment(rows + 1, i + 1, comment);
}
}
// 写入一行数据末尾处理
rowEnd(row0, row);
}
protected void rowEnd(org.ttzero.excel.reader.Row row0, Row row) {
// 占位符是否已消费结束
boolean consumerEnd = true;
if (!rowIterator.consumerNamespaces.isEmpty()) {
for (String vwKey : rowIterator.consumerNamespaces) {
ValueWrapper vw = namespaceMapper.get(vwKey);
if (++vw.i < vw.list.size()) consumerEnd = false;
// 加载更多数据
else if (vw.supplier != null) {
List list = vw.supplier.apply(vw.size, !vw.list.isEmpty() ? vw.list.get(vw.list.size() - 1) : null);
if (list != null && !list.isEmpty()) {
vw.list = list;
vw.i = 0;
vw.size += list.size();
consumerEnd = false;
} else vw.option = -1;
} else vw.option = -1;
}
}
// Ark
if (consumerEnd) rowCommit(row0, row);
}
protected void rowCommit(org.ttzero.excel.reader.Row row0, org.ttzero.excel.entity.Row row) {
PreCell pn;
Object e;
int len = Math.max(row0.getLastColumnIndex(), 0);
if (rowIterator.newRow && validations0 != null && row.getIndex() > row0.getRowNum()) {
for (Validation val : validations0) {
for (Dimension sqref : val.sqrefList) {
if (sqref.firstRow == row0.getRowNum()) {
sqref.verticalMove(row.getIndex() - row0.getRowNum() + 1);
ListValidation lv;
if (val instanceof ListValidation && StringUtil.isNotEmpty((lv = (ListValidation) val).indirect)) {
Dimension dim = Dimension.of(lv.indirect);
dim.verticalMove(row.getIndex() - row0.getRowNum() + 1);
lv.indirect = dim.toString();
}
}
}
}
}
if (rowIterator.hasFillCell) {
for (int i = row0.getFirstColumnIndex(); i < len; i++) {
if ((pn = rowIterator.preNodes[i]) != null && pn.validation != null) {
for (Dimension sqref : pn.validation.sqrefList) {
sqref.lastRow += pn.v;
}
}
}
pi++;
pf = preCells.length > pi && preCells[pi] != null && preCells[pi].length >= 1 ? preCells[pi][0].row : -1;
}
// 过滤行列重算
if (afr == row0.getRowNum() && (e = getExtPropValue(Const.ExtendPropertyKey.AUTO_FILTER)) instanceof Dimension) {
((Dimension) e).verticalMove(row.getIndex() - afr + 1);
afr = -1;
}
rowIterator.commit();
}
/**
* 获取占位符的实际值
*
* @param node 占位符节点信息
* @return 值
*/
protected Object getNodeValue(Node node) {
// 纯文本
if ((node.option & 1) == 0) return node.val;
ValueWrapper vw = namespaceMapper.get(node.namespace);
Object e = null;
if (vw != null) {
switch (vw.option) {
case 1: e = getObjectValue(vw.accessibleObjectMap.get(node.val), vw.o, node.val); break;
case 2: e = vw.map.get(node.val); break;
case 3: e = ((Map<String, Object>) vw.list.get(vw.i)).get(node.val); break;
case 4: e = getObjectValue(vw.accessibleObjectMap.get(node.val), vw.list.get(vw.i), node.val); break;
default:
}
}
return e;
}
/**
* 反射获取对象的值
*
* @param ao Method 或 Field
* @param o 对象
* @param key 占位符
* @return 值
*/
protected Object getObjectValue(AccessibleObject ao, Object o, String key) {
if (o == null) return null;
Object e = null;
try {
if (ao instanceof Method) e = ((Method) ao).invoke(o);
else if (ao instanceof Field) e = ((Field) ao).get(o);
else e = o;
} catch (IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Invoke {} value error", key, ex);
}
return e;
}
protected void fillValue(Row row, Cell cell, PreCell pn, Column emptyColumn) {
Object e;
if (pn.nodes.length == 1) {
e = getNodeValue(pn.nodes[0]);
int type = pn.nodes[0].getType();
if (e != null) {
Class<?> clazz = e.getClass();
emptyColumn.setClazz(clazz);
switch (type) {
// Hyperlink
case 1: if (isString(clazz)) cell.setHyperlink(e.toString()); break;
// Media
case 2:
if (isString(clazz)) {
cellValueAndStyle.writeAsMedia(row, cell, e.toString(), emptyColumn, String.class);
} else if (Path.class.isAssignableFrom(clazz)) {
cell.setPath((Path) e);
} else if (File.class.isAssignableFrom(clazz)) {
cell.setPath(((File) e).toPath());
} else if (InputStream.class.isAssignableFrom(clazz)) {
cell.setInputStream((InputStream) e);
} else if (clazz == byte[].class) {
cell.setBinary((byte[]) e);
} else if (ByteBuffer.class.isAssignableFrom(clazz)) {
cell.setByteBuffer((ByteBuffer) e);
}
break;
default:
cellValueAndStyle.setCellValue(row, cell, e, emptyColumn, clazz, false);
// 日期类型添加默认format
if (cell.t == Cell.DATETIME || cell.t == Cell.DATE || cell.t == Cell.TIME) {
datetimeCell(workbook.getStyles(), cell);
}
}
} else cell.emptyTag();
// 序列的dimension纵向+1
if (type == 3) pn.v++;
} else {
int k = 0;
for (Node node : pn.nodes) {
e = getNodeValue(node);
if (e != null) {
String s = e.toString();
int vn = s.length();
if (vn + k > pn.cb.length) pn.cb = Arrays.copyOf(pn.cb, vn + k + 128);
s.getChars(0, vn, pn.cb, k);
k += vn;
}
}
cell.setString(new String(pn.cb, 0, k));
}
}
/**
* 日期类型添加默认format
*
* @param styles Styles
* @param cell 单元格
*/
protected void datetimeCell(Styles styles, Cell cell) {
defaultDatetimeCell(styles, cell);
}
@Override
public void afterSheetDataWriter(int total) {
super.afterSheetDataWriter(total);
// 添加图片
if (pictures != null) {
try {
for (Drawings.Picture p : pictures) {
if (p == null || p.isBackground()) continue;
sheetWriter.writePicture(toWritablePicture(p));
}
} catch (IOException e) {
LOGGER.warn("Copy pictures failed.", e);
}
}
// 添加合并
if (mergeCells != null) putExtProp(Const.ExtendPropertyKey.MERGE_CELLS, mergeCells);
// // TODO 重置过滤位置
// Object o = getExtPropValue(Const.ExtendPropertyKey.AUTO_FILTER);
// if (o instanceof Dimension) {
// Dimension autoFilter = (Dimension) o;
// putExtProp(Const.ExtendPropertyKey.AUTO_FILTER, autoFilter);
// }
// 数据验证
if (validations0 != null && !validations0.isEmpty()) {
putExtProp(Const.ExtendPropertyKey.DATA_VALIDATION, validations0);
}
}
@Override
public void close() throws IOException {
super.close();
if (reader != null) {
reader.close();
reader = null;
}
if (templateStream != null) {
templateStream.close();
templateStream = null;
}
if (shouldDelete) FileUtil.rm(templatePath);
rowIterator = null;
namespaceMapper = null;
}
/**
* 将图片转为导出格式
*
* @param pic 图片
* @return 可导出图片
*/
public static Picture toWritablePicture(Drawings.Picture pic) {
Picture p = new Picture();
p.localPath = pic.getLocalPath();
p.row = pic.getDimension().firstRow - 1;
p.col = pic.getDimension().firstColumn - 1;
p.toRow = pic.getDimension().lastRow - 1;
p.toCol = pic.getDimension().lastColumn - 1;
p.padding = pic.getPadding();
p.revolve = pic.getRevolve();
p.property = pic.getProperty();
p.effect = pic.getEffect();
return p;
}
/**
* 预处理样式和占位符
*
* @param originalSheet 模板工作表
* @return 模板工作表行迭代器
*/
protected CommitRowSetIterator prepare(org.ttzero.excel.reader.Sheet originalSheet) {
// 模板文件样式
Styles styles0 = reader.getStyles(), styles = workbook.getStyles();
// 样式缓存
if (styleMap == null) styleMap = writeAsExcel ? new HashMap<>() : Collections.emptyMap();
int prefixLen = prefix.length(), suffixLen = suffix.length(), pf = 0;
for (Iterator<org.ttzero.excel.reader.Row> iter = originalSheet.iterator(); iter.hasNext(); ) {
org.ttzero.excel.reader.Row row = iter.next();
int index = 0;
for (int i = row.getFirstColumnIndex(), end = row.getLastColumnIndex(); i < end; i++) {
Cell cell = row.getCell(i);
// 复制样式
if (writeAsExcel && !styleMap.containsKey(cell.xf)) {
// 复制样式添加进样式表
styleMap.put(cell.xf, copyStyle(styles0, styles, cell.xf));
}
// 判断字符串是否包含占位符,可以是一个或多个
if (row.getCellType(cell) == CellType.STRING) {
String v = row.getString(cell);
// 预处理单元格的值
PreCell preCell = prepareCellValue(row.getRowNum(), i, v, prefixLen, suffixLen);
if (preCell != null) {
if (preCells == null) preCells = new PreCell[10][];
PreCell[] pns;
if (index == 0) {
if (pf >= preCells.length) preCells = Arrays.copyOf(preCells, preCells.length + 10);
preCells[pf++] = pns = new PreCell[Math.min(end - i, 10)];
} else if (index >= (pns = preCells[pf - 1]).length)
preCells[pf - 1] = pns = Arrays.copyOf(pns, pns.length + 10);
pns[index++] = preCell;
}
}
}
if (index > 0 && preCells[pf - 1].length > index) preCells[pf - 1] = Arrays.copyOf(preCells[pf - 1], index);
}
return new CommitRowSetIterator((RowSetIterator) originalSheet.reset().iterator());
}
/**
* 复制样式
*
* @param srcStyles 源样式表
* @param distStyle 目标样式表
* @param copyXf 样式索引
* @return 复制样式在目标样式表中的索引
*/
protected static int copyStyle(Styles srcStyles, Styles distStyle, int copyXf) {
int style = srcStyles.getStyleByIndex(copyXf), xf = 0;
// 字体
Font font = srcStyles.getFont(style);
if (font != null) xf |= distStyle.addFont(font.clone());
// 填充
Fill fill = srcStyles.getFill(style);
if (fill != null) xf |= distStyle.addFill(fill.clone());
// 边框
Border border = srcStyles.getBorder(style);
if (border != null) xf |= distStyle.addBorder(border.clone());
// 格式化
NumFmt numFmt = srcStyles.getNumFmt(style);
if (numFmt != null) xf |= distStyle.addNumFmt(numFmt.clone());
// 水平对齐
xf |= srcStyles.getHorizontal(style);
// 垂直对齐
xf |= srcStyles.getVertical(style);
// 自动折行
xf |= srcStyles.getWrapText(style);
return distStyle.of(xf);
}
/**
* 解析公共数据
*
* @param originalSheet 源模板工作表
* @return 列数
*/
protected int prepareCommonData(org.ttzero.excel.reader.FullSheet originalSheet) {
// 获取列属性
int len = 0;