P15GEN2\59518
2025-10-10 9f6890646993d16260d4201d613c092132856127
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
package foundation.io.file;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Clob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
import foundation.data.entity.Entity;
import foundation.data.entity.EntitySet;
import foundation.data.meta.field.FieldWriter;
import foundation.data.meta.field.FieldsRuntime;
import foundation.io.define.DataIO;
import foundation.io.engine.ISheetWriter;
import foundation.io.engine.IWorkBookWriter;
import foundation.io.mapping.MappingsRuntime;
import foundation.io.object.Headers;
import foundation.io.object.Titles;
import foundation.util.MapList;
import foundation.util.Util;
import foundation.value.ValueType;
 
 
public class BookStandardWriter extends IWorkBookWriter implements ISheetWriter {
 
    private File file;
    private FileInputStream inputStream;
    private XSSFWorkbook workbook;
    private MapList<String, Sheet> sheetList;
    
    private Sheet sheet;
    private int titleRowNo;
    private int dataRowNo;
    private Row firstDataRow;
    private CellStyle[] cellStyles;
    private CellStyle errorCellStyles;
    private int currentRowNo;
    private int columnCount;
    private MappingsRuntime mappingsRuntime;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private static String resultFieldName = "导入反馈";
    
    public BookStandardWriter(File file, int batchCount) throws IOException {
        this.file = file;
        
        inputStream = new FileInputStream(file);
        workbook = new XSSFWorkbook(inputStream);
        
        sheetList = new MapList<String, Sheet>();
        
        for (Sheet sheet: workbook) {
            sheetList.add(sheet.getSheetName(), sheet);
        }
    }
 
    @Override
    public ISheetWriter openSheetWriter(DataIO dataIO) {
        this.titleRowNo = dataIO.getToTitleRowNo();
        this.dataRowNo = dataIO.getToDataRowNo();
        
        String sheetName = dataIO.getToName();
        
        sheet = sheetList.get(sheetName);
        if (sheet == null) {
            sheet = sheetList.get(0);
        }
        
        if (sheet == null) {
            sheet = workbook.createSheet(sheetName);
        }
 
        currentRowNo = -1;
        
        firstDataRow = sheet.getRow(dataRowNo);
        if (firstDataRow == null) {
            firstDataRow = sheet.createRow(dataRowNo);
        }
        
        return this;
    }
    
    @Override
    public Headers readHeaders() {
        Headers headers = new Headers();
        
        Row titleRow = sheet.getRow(titleRowNo);
        
        columnCount = titleRow.getLastCellNum();
        Cell titleCell, valueCell;
        
        for (int i = 0; i < columnCount; i++) {
            //1. 读取标题列
            titleCell = (titleRow != null) ? titleRow.getCell(i) : null;
            String title = (titleCell != null) ? getCellStringValue(titleCell) : null;
            
            //2. 读取第一行数据
            valueCell = firstDataRow.getCell(i);
            String value = (valueCell != null) ? getCellStringValue(valueCell) : null;
            
            //3. 添加到  header 中
            headers.addOne(i, title, value);
        }
        
        return headers;
    }
 
    private String getCellStringValue(Cell cell) {
        try {
            return cell.getStringCellValue();
        }
        catch (Exception e) {
            return null;
        }
    }
 
    @Override
    public void writeTitles(Titles titles) {
        Row titleRow = sheet.getRow(titleRowNo);
                
        if (titleRow == null) {
            titleRow = sheet.createRow(titleRowNo);
        }
        
        Cell cell;
        
        for (int i = 0; i < columnCount; i++) {
            cell = titleRow.getCell(i);
            
            if (cell == null) {
                cell = titleRow.createCell(i);
            }
            
            String title = titles.get(i);
            cell.setCellValue(String.valueOf(title));
        }        
    }
 
 
    @Override
    public void writeErrorTitle() {
        Row titleRow = sheet.getRow(titleRowNo);
        columnCount = titleRow.getLastCellNum();
        
        Cell cell = titleRow.createCell(columnCount);
 
        createErrrorCellStyles();
        cell.setCellStyle(errorCellStyles);
        cell.setCellValue(resultFieldName);
    }
 
    @Override
    public void parepareWriteData() {
        //1. 创建格式
        createDataCellStyles();
        
        //2. 清空第一个数据行上的数据
        clearFirstDataRow();
    }
    
    private void createDataCellStyles() {
        cellStyles = new CellStyle[columnCount];
        for (int i = 0; i < columnCount; i++) {
            Cell cell = firstDataRow.getCell(i);
            
            if (cell == null) {
                continue;
            }
            
            cellStyles[i] = cell.getCellStyle();
        }
    }
    
    private void createErrrorCellStyles() {
        errorCellStyles = workbook.createCellStyle();
        
        errorCellStyles.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        errorCellStyles.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        errorCellStyles.setBorderRight(BorderStyle.THIN);
        
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short)11);
        errorCellStyles.setFont(font);
    }
    
    private void clearFirstDataRow() {
        Row dataRow = sheet.getRow(dataRowNo);
        
        if (dataRow == null) {
            return;
        }        
        
        Cell cell;
        for (int i = 0; i < columnCount; i++) {
            cell = dataRow.getCell(i);
            
            if (cell == null) {
                continue;
            }
            
            cell.setBlank();
        }
    }
 
    @Override
    public int writeData(EntitySet entitySet) {
        int result = 0;
        
        if (currentRowNo < 0) {
            currentRowNo = dataRowNo;
        }
        
        int[] fromIndexes = mappingsRuntime.getFromIndex();
        int[] toIndexes = mappingsRuntime.getToIndex();
        String[] formatMap = mappingsRuntime.getFormatIndexs();
        int dataSize = toIndexes.length;
        
        Row dataRow = null; Cell cell; 
        CellStyle cellStyle; int fromIndex, toIndex; String formatStr;
        FieldWriter fieldWriter; Object[] data;
        
        FieldsRuntime fields = entitySet.getEntityMeta();
        ValueType[] valueTypes = fields.getValueTypes();
        FieldWriter[] fieldWriters = fields.getWriters();
        
        for (Entity entity: entitySet) {
            data = entity.getDataArray();
            dataRow = sheet.getRow(currentRowNo);
            
            if (dataRow == null) {
                dataRow = sheet.createRow(currentRowNo);
            }
            
            dataRow.setRowStyle(firstDataRow.getRowStyle());
            dataRow.setHeight(firstDataRow.getHeight());
            dataRow.setHeightInPoints(firstDataRow.getHeightInPoints());
            
            for (int i = 0; i < columnCount; i++) {
                cellStyle = cellStyles[i]; 
                
                if (cellStyle == null) {
                    continue;
                }
                
                //1. 单元格
                cell = dataRow.getCell(i);
                
                if (cell == null) {
                    cell = dataRow.createCell(i);
                }
                
                //2. 设置格式
                cell.setCellStyle(cellStyle);
            }
            
            for (int i = 0; i < dataSize; i++) {
                toIndex = toIndexes[i];
                cell = dataRow.getCell(toIndex);
                
                //3. 获取数据
                fromIndex = fromIndexes[i]; 
                fieldWriter = fieldWriters[fromIndex];
                Object value = fieldWriter.getValue(data[fromIndex]);
                formatStr = formatMap[i];
                
                //4. 数据写入
                writeOneCell(cell, valueTypes[fromIndex], formatStr, value);
            }
            
            currentRowNo++;
            result++;
        }
 
        return result;
    }
    
    @Override
    public void writeImg(EntitySet fileSet) throws Exception {
//        FileInputStream imgFis = new FileInputStream("C:\\Users\\59518\\Desktop\\groupBRegion.png");
//        byte[] imageBytes = IOUtils.toByteArray(imgFis);
//        int pictureIndex = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
//
//        // 创建绘图对象和锚点
//        CreationHelper helper = workbook.getCreationHelper();
//        Drawing<?> drawing = sheet.createDrawingPatriarch();
//        ClientAnchor anchor = helper.createClientAnchor();
//        anchor.setCol1(0); // 图片起始列
//        anchor.setRow1(0); // 图片起始行
//
//        // 插入图片并调整大小
//        Picture picture = drawing.createPicture(anchor, pictureIndex);
//        picture.resize(); // 适应单元格大小
    }
        
        
    @Override
    public int writeErrors(EntitySet entitySet) {
        int result = 0;
        if (currentRowNo < 0) {
            currentRowNo = dataRowNo;
        }
        
        Row dataRow = null; Cell cell;
 
        int[] fromIndexes = mappingsRuntime.getFromIndex();
        int dataSize = fromIndexes.length;
        
        CellStyle cellStyle = null; int fromIndex; String formatStr;
        FieldWriter fieldWriter; Object[] data;
        
        FieldsRuntime fields = entitySet.getEntityMeta();
        ValueType[] valueTypes = fields.getValueTypes();
        FieldWriter[] fieldWriters = fields.getWriters();
        
        for (Entity entity: entitySet) {
            data = entity.getDataArray();
            dataRow = sheet.getRow(currentRowNo);
            
            if (dataRow == null) {
                dataRow = sheet.createRow(currentRowNo);
            }
            
            dataRow.setRowStyle(firstDataRow.getRowStyle());
            dataRow.setHeight(firstDataRow.getHeight());
            dataRow.setHeightInPoints(firstDataRow.getHeightInPoints());
            
            //1. 创建样式
            for (int i = 0; i < columnCount; i++) {
                cellStyle = cellStyles[i]; 
                
                if (cellStyle == null) {
                    continue;
                }
                
                cell = dataRow.getCell(i);
                
                if (cell == null) {
                    cell = dataRow.createCell(i);
                }
                
                cell.setCellStyle(cellStyle);
            }
            
            cell = dataRow.createCell(columnCount);
            cell.setCellStyle(cellStyle);
            
            for (int i = 0; i < dataSize; i++) {
                cell = dataRow.getCell(i);
                
                //2. 获取数据
                fromIndex = fromIndexes[i]; 
                fieldWriter = fieldWriters[fromIndex];
                Object value = fieldWriter.getValue(data[fromIndex]);
                
                //4. 数据写入
                writeOneCell(cell, valueTypes[fromIndex], null, value);
            }
            
            currentRowNo++;
            result++;
        }
        
        return result;
    }
    
    protected void writeOneCell(Cell cell, ValueType valueType, String format, Object value) {
        if (value == null) {
            return ;
        }
 
        if (ValueType.Decimal == valueType) {
            double cellValue = ((BigDecimal)value).doubleValue();
            
            if (Util.isEmpty(format)) {
                cell.setCellValue(cellValue);
            }
            else if ("K".equals(format)) {
                cellValue = cellValue/1000;
                cell.setCellValue(cellValue);
            }
            else if (format.endsWith("%")) {
                int scale = Integer.valueOf(format.substring(0, format.length() - 1));
                BigDecimal rate = new BigDecimal(cellValue*100);
                rate = rate.setScale(scale, RoundingMode.HALF_UP);
                cell.setCellValue(rate + "%");
            }
        }
        else if (ValueType.Double == valueType) {
            double cellValue = (Double)value;
            if (Util.isEmpty(format)) {
                cell.setCellValue(cellValue);
            }
            else if ("K".equals(format)) {
                cellValue = cellValue/1000;
                cell.setCellValue(cellValue);
            }
            else if (format.endsWith("%")) {
                int scale = Integer.valueOf(format.substring(0, format.length() - 1));
                BigDecimal rate = new BigDecimal(cellValue*100);
                rate = rate.setScale(scale, RoundingMode.HALF_UP);
                cell.setCellValue(rate + "%");
            }
        }
        else if (ValueType.Int == valueType) {
            Integer cellValue = (Integer)value;
            if (Util.isEmpty(format)) {
                cell.setCellValue(cellValue);
            }
            else if ("K".equals(format)) {
                cellValue = cellValue/1000;
                cell.setCellValue(cellValue);
            }
            else if (format.endsWith("%")) {
                int scale = Integer.valueOf(format.substring(0, format.length() - 1));
                BigDecimal rate = new BigDecimal(cellValue*100);
                rate = rate.setScale(scale, RoundingMode.HALF_UP);
                cell.setCellValue(rate + "%");
            }
        }   
        else if (ValueType.Long == valueType) {
            Long cellValue = (Long)value;
            if (Util.isEmpty(format)) {
                cell.setCellValue(cellValue);
            }
            else if ("K".equals(format)) {
                cellValue = cellValue/1000;
                cell.setCellValue(cellValue);
            }
            else if (format.endsWith("%")) {
                int scale = Integer.valueOf(format.substring(0, format.length() - 1));
                BigDecimal rate = new BigDecimal(cellValue*100);
                rate = rate.setScale(scale, RoundingMode.HALF_UP);
                cell.setCellValue(rate + "%");
            }
        } 
        else if (ValueType.Float == valueType) {
            Float cellValue = (Float)value;
            if (Util.isEmpty(format)) {
                cell.setCellValue(cellValue);
            }
            else if ("K".equals(format)) {
                cellValue = cellValue/1000;
                cell.setCellValue(cellValue);
            }
            else if (format.endsWith("%")) {
                int scale = Integer.valueOf(format.substring(0, format.length() - 1));
                BigDecimal rate = new BigDecimal(cellValue*100);
                rate = rate.setScale(scale, RoundingMode.HALF_UP);
                cell.setCellValue(rate + "%");
            }
        }
        else if (ValueType.Date == valueType) {
            String formatDate = dateFormat.format((Date)value);
            cell.setCellValue(formatDate);
        }
        else if (ValueType.Clob == valueType) {
            Clob clob = (Clob)value;
            
            try {
                cell.setCellValue(clob.getSubString((long)1, (int)clob.length()));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        else {
            cell.setCellValue(String.valueOf(value));
        }
    }
    
    @Override
    public void close() {
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            try {
                workbook.write(outputStream);
                workbook.close();
                close = true;
            }
            finally {
                outputStream.close();
            }
        }
        catch (Exception e) {
            logger.error("close work book error: {}", e.getMessage());
        }
    }
    
 
    @Override
    public void setMappingRuntime(MappingsRuntime mappingsRuntime) {
        this.mappingsRuntime = mappingsRuntime;
    }
}