VerticalRecordsProcessor.java

  1. package com.gh.mygreen.xlsmapper.fieldprocessor.impl;

  2. import java.lang.annotation.Annotation;
  3. import java.lang.reflect.Array;
  4. import java.lang.reflect.InvocationTargetException;
  5. import java.lang.reflect.Method;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.Collection;
  9. import java.util.HashMap;
  10. import java.util.LinkedHashMap;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Optional;
  14. import java.util.concurrent.atomic.AtomicInteger;
  15. import java.util.stream.Collectors;

  16. import org.apache.poi.ss.usermodel.BorderStyle;
  17. import org.apache.poi.ss.usermodel.Cell;
  18. import org.apache.poi.ss.usermodel.CellStyle;
  19. import org.apache.poi.ss.usermodel.DataValidation;
  20. import org.apache.poi.ss.usermodel.Name;
  21. import org.apache.poi.ss.usermodel.Sheet;
  22. import org.apache.poi.ss.usermodel.Workbook;
  23. import org.apache.poi.ss.util.AreaReference;
  24. import org.apache.poi.ss.util.CellRangeAddress;
  25. import org.apache.poi.ss.util.CellRangeAddressList;
  26. import org.apache.poi.ss.util.CellReference;

  27. import com.gh.mygreen.xlsmapper.AnnotationInvalidException;
  28. import com.gh.mygreen.xlsmapper.Configuration;
  29. import com.gh.mygreen.xlsmapper.LoadingWorkObject;
  30. import com.gh.mygreen.xlsmapper.NeedProcess;
  31. import com.gh.mygreen.xlsmapper.SavingWorkObject;
  32. import com.gh.mygreen.xlsmapper.XlsMapperException;
  33. import com.gh.mygreen.xlsmapper.annotation.ArrayDirection;
  34. import com.gh.mygreen.xlsmapper.annotation.RecordTerminal;
  35. import com.gh.mygreen.xlsmapper.annotation.XlsArrayColumns;
  36. import com.gh.mygreen.xlsmapper.annotation.XlsColumn;
  37. import com.gh.mygreen.xlsmapper.annotation.XlsIgnorable;
  38. import com.gh.mygreen.xlsmapper.annotation.XlsMapColumns;
  39. import com.gh.mygreen.xlsmapper.annotation.XlsNestedRecords;
  40. import com.gh.mygreen.xlsmapper.annotation.XlsRecordFinder;
  41. import com.gh.mygreen.xlsmapper.annotation.XlsRecordOption;
  42. import com.gh.mygreen.xlsmapper.annotation.XlsRecordOption.OverOperation;
  43. import com.gh.mygreen.xlsmapper.annotation.XlsRecordOption.RemainedOperation;
  44. import com.gh.mygreen.xlsmapper.annotation.XlsVerticalRecords;
  45. import com.gh.mygreen.xlsmapper.cellconverter.CellConverter;
  46. import com.gh.mygreen.xlsmapper.cellconverter.TypeBindException;
  47. import com.gh.mygreen.xlsmapper.fieldaccessor.FieldAccessor;
  48. import com.gh.mygreen.xlsmapper.fieldprocessor.AbstractFieldProcessor;
  49. import com.gh.mygreen.xlsmapper.fieldprocessor.CellNotFoundException;
  50. import com.gh.mygreen.xlsmapper.fieldprocessor.MergedRecord;
  51. import com.gh.mygreen.xlsmapper.fieldprocessor.NestedRecordMergedSizeException;
  52. import com.gh.mygreen.xlsmapper.fieldprocessor.ProcessCase;
  53. import com.gh.mygreen.xlsmapper.fieldprocessor.RecordFinder;
  54. import com.gh.mygreen.xlsmapper.fieldprocessor.RecordHeader;
  55. import com.gh.mygreen.xlsmapper.fieldprocessor.RecordMethodCache;
  56. import com.gh.mygreen.xlsmapper.fieldprocessor.RecordMethodFacatory;
  57. import com.gh.mygreen.xlsmapper.fieldprocessor.RecordsProcessorUtil;
  58. import com.gh.mygreen.xlsmapper.localization.MessageBuilder;
  59. import com.gh.mygreen.xlsmapper.util.CellFinder;
  60. import com.gh.mygreen.xlsmapper.util.CellPosition;
  61. import com.gh.mygreen.xlsmapper.util.FieldAccessorUtils;
  62. import com.gh.mygreen.xlsmapper.util.POIUtils;
  63. import com.gh.mygreen.xlsmapper.util.Utils;
  64. import com.gh.mygreen.xlsmapper.validation.fieldvalidation.FieldFormatter;
  65. import com.gh.mygreen.xlsmapper.xml.AnnotationReadException;
  66. import com.gh.mygreen.xlsmapper.xml.AnnotationReader;


  67. /**
  68.  * アノテーション{@link XlsVerticalRecords}を処理するクラス。
  69.  *
  70.  * @version 2.1
  71.  * @author Naoki Takezoe
  72.  * @author T.TSUCHIE
  73.  *
  74.  */
  75. public class VerticalRecordsProcessor extends AbstractFieldProcessor<XlsVerticalRecords>{

  76.     @Override
  77.     public void loadProcess(final Sheet sheet, final Object beansObj, final XlsVerticalRecords anno,
  78.             final FieldAccessor accessor, final Configuration config, final LoadingWorkObject work) throws XlsMapperException {

  79.         if(!accessor.isWritable()) {
  80.             // セルの値を書き込むメソッド/フィールドがない場合はスキップ
  81.             return;
  82.         }
  83.        
  84.         if(!Utils.isLoadCase(anno.cases())) {
  85.             return;
  86.         }

  87.         final Class<?> clazz = accessor.getType();
  88.         if(Collection.class.isAssignableFrom(clazz)) {

  89.             Class<?> recordClass = anno.recordClass();
  90.             if(recordClass == Object.class) {
  91.                 recordClass = accessor.getComponentType();
  92.             }

  93.             final List<?> value = loadRecords(sheet, beansObj, anno, accessor, recordClass, config, work);
  94.             if(value != null) {
  95.                 @SuppressWarnings({"unchecked", "rawtypes"})
  96.                 Collection<?> collection = Utils.convertListToCollection(value, (Class<Collection>)clazz, config.getBeanFactory());
  97.                 accessor.setValue(beansObj, collection);
  98.             }
  99.         } else if(clazz.isArray()) {

  100.             Class<?> recordClass = anno.recordClass();
  101.             if(recordClass == Object.class) {
  102.                 recordClass = accessor.getComponentType();
  103.             }

  104.             final List<?> value = loadRecords(sheet, beansObj, anno, accessor, recordClass, config, work);
  105.             if(value != null) {
  106.                 final Object array = Array.newInstance(recordClass, value.size());
  107.                 for(int i=0; i < value.size(); i++) {
  108.                     Array.set(array, i, value.get(i));
  109.                 }

  110.                 accessor.setValue(beansObj, array);
  111.             }

  112.         } else {
  113.             throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.notSupportType")
  114.                     .var("property", accessor.getNameWithClass())
  115.                     .varWithAnno("anno", XlsVerticalRecords.class)
  116.                     .varWithClass("actualType", clazz)
  117.                     .var("expectedType", "Collection(List/Set) or Array")
  118.                     .format());
  119.         }

  120.     }

  121.    private List<?> loadRecords(final Sheet sheet, final Object beansObj, final XlsVerticalRecords anno, final FieldAccessor accessor,
  122.            final Class<?> recordClass, final Configuration config, final LoadingWorkObject work) throws XlsMapperException {

  123.         // get table starting position
  124.         final Optional<CellPosition> initPosition = getHeaderPosition(sheet, anno, accessor, config);
  125.         if(!initPosition.isPresent()) {
  126.             return null;
  127.         }

  128.         // ラベルの設定
  129.         if(Utils.isNotEmpty(anno.tableLabel())) {
  130.             final Optional<Cell> tableLabelCell = CellFinder.query(sheet, anno.tableLabel(), config).findOptional();
  131.             tableLabelCell.ifPresent(c -> {
  132.                 final String label = POIUtils.getCellContents(c, config.getCellFormatter());
  133.                 accessor.setLabel(beansObj, label);

  134.             });
  135.         }

  136.         final int initColumn = initPosition.get().getColumn();
  137.         final int initRow = initPosition.get().getRow();

  138.         int hColumn = initColumn;
  139.         int hRow = initRow;

  140.         // get header columns.
  141.         final List<RecordHeader> headers = new ArrayList<>();
  142.         int rangeCount = 1;
  143.         while(true){
  144.             try {
  145.                 Cell cell = POIUtils.getCell(sheet, hColumn, hRow);
  146.                 while(POIUtils.isEmptyCellContents(cell, config.getCellFormatter()) && rangeCount < anno.range()){
  147.                     cell = POIUtils.getCell(sheet, hColumn, hRow + rangeCount);
  148.                     rangeCount++;
  149.                 }

  150.                 String cellValue = POIUtils.getCellContents(cell, config.getCellFormatter());
  151.                 if(Utils.isEmpty(cellValue)){
  152.                     break;
  153.                 } /*else {
  154.                     for(int j=hColumn; j > initColumn; j--){
  155.                         final Cell tmpCell = POIUtils.getCell(sheet, j, hRow);
  156.                         if(!POIUtils.isEmptyCellContents(tmpCell, config.getCellFormatter())){
  157.                             cell = tmpCell;
  158.                             break;
  159.                         }
  160.                     }
  161.                 }*/

  162.                 headers.add(new RecordHeader(cellValue, cell.getRowIndex() - initRow));
  163.                 hRow = hRow + rangeCount;
  164.                 rangeCount = 1;

  165.                 // 結合しているセルの場合は、はじめのセルだけ取得して、後は結合分スキップする。
  166.                 CellRangeAddress mergedRange = POIUtils.getMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex());
  167.                 if(mergedRange != null) {
  168.                     hRow = hRow + (mergedRange.getLastRow() - mergedRange.getFirstRow());
  169.                 }

  170.             } catch(ArrayIndexOutOfBoundsException ex){
  171.                 break;
  172.             }

  173.             if(anno.headerLimit() > 0 && headers.size() >= anno.headerLimit()){
  174.                 break;
  175.             }
  176.         }

  177.         // データ行の開始位置の調整
  178.         hColumn += anno.headerRight();
  179.         CellPosition startPosition = CellPosition.of(initRow, hColumn);

  180.         // 独自の開始位置を指定する場合
  181.         final Optional<XlsRecordFinder> finderAnno = accessor.getAnnotation(XlsRecordFinder.class);
  182.         if(finderAnno.isPresent()) {
  183.             final RecordFinder finder = config.createBean(finderAnno.get().value());
  184.             startPosition = finder.find(ProcessCase.Load, finderAnno.get().args(), sheet, startPosition, beansObj, config);

  185.         }

  186.         return loadRecords(sheet, headers, anno, startPosition, 0, accessor, recordClass, config, work);
  187.    }

  188.    private List<?> loadRecords(final Sheet sheet, final List<RecordHeader> headers,
  189.            final XlsVerticalRecords anno,
  190.            final CellPosition initPosition, final int parentMergedSize,
  191.            final FieldAccessor accessor, final Class<?> recordClass,
  192.            final Configuration config, final LoadingWorkObject work) throws XlsMapperException {

  193.         final List<Object> result = new ArrayList<>();

  194.         final int initColumn = initPosition.getColumn();
  195.         final int initRow = initPosition.getRow();

  196.         final int maxColumn = initColumn + parentMergedSize;
  197.         int hColumn = initColumn;

  198.         // Check for columns
  199.         RecordsProcessorUtil.checkColumns(sheet, recordClass, headers, work.getAnnoReader(), config);
  200.         RecordsProcessorUtil.checkMapColumns(sheet, recordClass, headers, work.getAnnoReader(), config);
  201.         RecordsProcessorUtil.checkArrayColumns(sheet, recordClass, headers, work.getAnnoReader(), config);

  202.         RecordTerminal terminal = anno.terminal();
  203.         if(terminal == null){
  204.             terminal = RecordTerminal.Empty;
  205.         }

  206.         // 各種レコードのコールバック用メソッドを抽出する
  207.         final RecordMethodCache methodCache = new RecordMethodFacatory(work.getAnnoReader(), config)
  208.                 .create(recordClass, ProcessCase.Load);

  209.         // レコードの見出しに対するカラム情報のキャッシュ
  210.         final Map<String, List<FieldAccessor>> propertiesCache = new HashMap<>();

  211.         // カラムに対するConverterのキャッシュ
  212.         final Map<String, CellConverter<?>> converterCache = new HashMap<>();

  213.         final int startHeaderIndex = getStartHeaderIndexForLoading(headers, recordClass, work.getAnnoReader(), config);

  214.         // get records
  215.         while(hColumn < POIUtils.getColumns(sheet)){

  216.             if(parentMergedSize > 0 && hColumn >= maxColumn) {
  217.                 // ネストしている処理のとき、最大の処理レコード数をチェックする。
  218.                 break;
  219.             }

  220.             boolean emptyFlag = true;
  221.             // recordは、マッピング先のオブジェクトのインスタンス。
  222.             final Object record = config.createBean(recordClass);

  223.             // パスの位置の変更
  224.             work.getErrors().pushNestedPath(accessor.getName(), result.size());

  225.             // execute PreProcess listener
  226.             methodCache.getListenerClasses().forEach(listenerClass -> {
  227.                 listenerClass.getPreLoadMethods().forEach(method -> {
  228.                     Utils.invokeNeedProcessMethod(listenerClass.getObject(), method, record, sheet, config, work.getErrors(), ProcessCase.Load);
  229.                 });
  230.             });

  231.             // execute PreProcess method
  232.             methodCache.getPreLoadMethods().forEach(method -> {
  233.                 Utils.invokeNeedProcessMethod(record, method, record, sheet, config, work.getErrors(), ProcessCase.Load);
  234.             });

  235.             final List<MergedRecord> mergedRecords = new ArrayList<>();

  236.             loadMapColumns(sheet, headers, mergedRecords, CellPosition.of(initRow, hColumn), recordClass, record, config, work);

  237.             loadArrayColumns(sheet, headers, mergedRecords, CellPosition.of(initRow, hColumn), recordClass, record, config, work);

  238.             for(int i=0; i < headers.size() && hColumn < POIUtils.getColumns(sheet); i++){
  239.                 final RecordHeader headerInfo = headers.get(i);
  240.                 int hRow = initRow + headerInfo.getInterval();
  241.                 final Cell cell = POIUtils.getCell(sheet, hColumn, hRow);

  242.                 // find end of the table
  243.                 if(!POIUtils.isEmptyCellContents(cell, config.getCellFormatter())){
  244.                     emptyFlag = false;
  245.                 }

  246.                 if(terminal==RecordTerminal.Border && i == startHeaderIndex){
  247.                     if(!POIUtils.getBorderTop(cell).equals(BorderStyle.NONE)){
  248.                         emptyFlag = false;
  249.                     } else {
  250.                         emptyFlag = true;
  251.                         break;
  252.                     }
  253.                 }

  254.                 if(!anno.terminateLabel().equals("")){
  255.                     if(Utils.matches(POIUtils.getCellContents(cell, config.getCellFormatter()), anno.terminateLabel(), config)){
  256.                         emptyFlag = true;
  257.                         break;
  258.                     }
  259.                 }

  260.                 // mapping from Excel columns to Object properties.
  261.                 final List<FieldAccessor> propeties = propertiesCache.computeIfAbsent(headerInfo.getLabel(), key -> {
  262.                     return FieldAccessorUtils.getColumnPropertiesByName(
  263.                             record.getClass(), work.getAnnoReader(), config, key)
  264.                             .stream()
  265.                             .filter(p -> p.isWritable())
  266.                             .collect(Collectors.toList());
  267.                 });

  268.                 for(FieldAccessor property : propeties) {
  269.                     Cell valueCell = cell;
  270.                     final XlsColumn column = property.getAnnotationNullable(XlsColumn.class);

  271.                     if(column.headerMerged() > 0){
  272.                         hRow = hRow + column.headerMerged();
  273.                         valueCell = POIUtils.getCell(sheet, hColumn, hRow);
  274.                     }

  275.                     // for merged cell
  276.                     if(POIUtils.isEmptyCellContents(valueCell, config.getCellFormatter())){
  277.                         CellStyle valueCellFormat = valueCell.getCellStyle();
  278.                         if(column.merged() && POIUtils.getBorderRight(valueCell).equals(BorderStyle.NONE)){
  279.                             for(int k=hColumn; k > initColumn; k--){
  280.                                 final Cell tmpCell = POIUtils.getCell(sheet, k, hRow);
  281.                                 final CellStyle tmpCellFormat = tmpCell.getCellStyle();

  282.                                 if(!POIUtils.getBorderLeft(tmpCell).equals(BorderStyle.NONE)){
  283.                                     break;
  284.                                 }

  285.                                 if(!POIUtils.isEmptyCellContents(tmpCell, config.getCellFormatter())){
  286.                                     valueCell = tmpCell;
  287.                                     break;
  288.                                 }
  289.                             }
  290.                         }
  291.                     }

  292.                     if(column.headerMerged() > 0){
  293.                         hRow = hRow - column.headerMerged();
  294.                     }

  295.                     CellRangeAddress mergedRange = POIUtils.getMergedRegion(sheet, valueCell.getRowIndex(), valueCell.getColumnIndex());
  296.                     if(mergedRange != null) {
  297.                         int mergedSize =  mergedRange.getLastColumn() - mergedRange.getFirstColumn() + 1;
  298.                         mergedRecords.add(new MergedRecord(headerInfo, mergedRange, mergedSize));
  299.                     } else {
  300.                         mergedRecords.add(new MergedRecord(headerInfo, CellRangeAddress.valueOf(POIUtils.formatCellAddress(valueCell)), 1));
  301.                     }

  302.                     if(!Utils.isLoadCase(column.cases())) {
  303.                         continue;
  304.                     }

  305.                     // set for value
  306.                     property.setPosition(record, CellPosition.of(valueCell));
  307.                     property.setLabel(record, headerInfo.getLabel());

  308.                     final Cell tempCommentCell = valueCell;
  309.                     property.getCommentSetter().ifPresent(setter ->
  310.                             config.getCommentOperator().loadCellComment(setter, tempCommentCell, record, property, config));
  311.                    
  312.                     final CellConverter<?> converter = converterCache.computeIfAbsent(property.getName(), key -> getCellConverter(property, config));
  313.                     if(converter instanceof FieldFormatter) {
  314.                         work.getErrors().registerFieldFormatter(property.getName(), property.getType(), (FieldFormatter<?>)converter, true);
  315.                     }

  316.                     try {
  317.                         final Object value = converter.toObject(valueCell);
  318.                         property.setValue(record, value);
  319.                     } catch(TypeBindException e) {
  320.                         work.addTypeBindError(e, valueCell, property.getName(), headerInfo.getLabel());
  321.                         if(!config.isContinueTypeBindFailure()) {
  322.                             throw e;
  323.                         }
  324.                     }
  325.                 }
  326.             }

  327.             // execute nested record
  328.             final int skipSize = loadNestedRecords(sheet, headers, mergedRecords, anno, CellPosition.of(initRow, hColumn), record, config, work);
  329.             if(parentMergedSize > 0 && skipSize > 0 && (hColumn + skipSize) > maxColumn) {
  330.                 // check over merged cell.
  331.                 String message = String.format("Over merged size. In sheet '%s' with columnIndex=%d, over the columnIndex=%s.",
  332.                         sheet.getSheetName(), hColumn + skipSize, maxColumn);
  333.                 throw new NestedRecordMergedSizeException(sheet.getSheetName(), skipSize, message);
  334.             }


  335.             if(emptyFlag){
  336.                 // パスの位置の変更
  337.                 work.getErrors().popNestedPath();
  338.                 break;
  339.             }

  340.             if(isAvailabledRecord(methodCache.getIgnoreableMethod(), record)) {
  341.                 // 有効なレコードのみ、処理を行う
  342.                 result.add(record);

  343.                 // set PostProcess listener
  344.                 methodCache.getListenerClasses().forEach(listenerClass -> {
  345.                     listenerClass.getPostLoadMethods().forEach(method -> {
  346.                         work.addNeedPostProcess(new NeedProcess(record, listenerClass.getObject(), method));
  347.                     });
  348.                 });

  349.                 // set PostProcess method
  350.                 methodCache.getPostLoadMethods().forEach(method -> {
  351.                     work.addNeedPostProcess(new NeedProcess(record, record, method));
  352.                 });

  353.             }

  354.             // パスの位置の変更
  355.             work.getErrors().popNestedPath();

  356.             if(skipSize > 0) {
  357.                 hColumn += skipSize;
  358.             } else {
  359.                 hColumn++;
  360.             }

  361.         }

  362.         return result;
  363.     }

  364.     /**
  365.      * 表の開始位置(見出し)の位置情報を取得する。
  366.      *
  367.      * @param sheet
  368.      * @param anno
  369.      * @param accessor
  370.      * @param config
  371.      * @return 表の開始位置。指定したラベルが見つからない場合、設定によりnullを返す。
  372.      * @throws AnnotationInvalidException アノテーションの値が不正で、表の開始位置が位置が見つからない場合。
  373.      * @throws CellNotFoundException 指定したラベルが見つからない場合。
  374.      */
  375.     private Optional<CellPosition> getHeaderPosition(final Sheet sheet, final XlsVerticalRecords anno,
  376.             final FieldAccessor accessor, final Configuration config) throws AnnotationInvalidException, CellNotFoundException {

  377.         if(Utils.isNotEmpty(anno.headerAddress())) {
  378.             try {
  379.                 return Optional.of(CellPosition.of(anno.headerAddress()));

  380.             } catch(IllegalArgumentException e) {
  381.                 throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.attr.invalidAddress")
  382.                         .var("property", accessor.getNameWithClass())
  383.                         .varWithAnno("anno", XlsVerticalRecords.class)
  384.                         .var("attrName", "headerAddress")
  385.                         .var("attrValue", anno.headerAddress())
  386.                         .format());

  387.             }

  388.         } else if(Utils.isNotEmpty(anno.tableLabel())) {
  389.             try {
  390.                 final Cell labelCell = CellFinder.query(sheet, anno.tableLabel(), config).findWhenNotFoundException();

  391.                 if(anno.tableLabelAbove()) {
  392.                     // 表の見出しが上にある場合、左側に補正する
  393.                     int initColumn = labelCell.getColumnIndex() + anno.right()-1;
  394.                     int initRow = labelCell.getRowIndex() + anno.bottom();
  395.                     return Optional.of(CellPosition.of(initRow, initColumn));

  396.                 } else {

  397.                     int initColumn = labelCell.getColumnIndex() + anno.right();
  398.                     int initRow = labelCell.getRowIndex();
  399.                     return Optional.of(CellPosition.of(initRow, initColumn));

  400.                 }

  401.             } catch(CellNotFoundException ex) {
  402.                 if(anno.optional()) {
  403.                     return Optional.empty();
  404.                 } else {
  405.                     throw ex;
  406.                 }
  407.             }
  408.         } else {
  409.             if(anno.headerRow() < 0) {
  410.                 throw  new AnnotationInvalidException(anno, MessageBuilder.create("anno.attr.min")
  411.                         .var("property", accessor.getNameWithClass())
  412.                         .varWithAnno("anno", XlsVerticalRecords.class)
  413.                         .var("attrName", "headerRow")
  414.                         .var("attrValue", anno.headerRow())
  415.                         .var("min", 0)
  416.                         .format());
  417.             }

  418.             if(anno.headerColumn() < 0) {
  419.                 throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.attr.min")
  420.                         .var("property", accessor.getNameWithClass())
  421.                         .varWithAnno("anno", XlsVerticalRecords.class)
  422.                         .var("attrName", "column")
  423.                         .var("attrValue", anno.headerColumn())
  424.                         .var("min", 0)
  425.                         .format());

  426.             }
  427.             return Optional.of(CellPosition.of(anno.headerRow(), anno.headerColumn()));
  428.         }
  429.     }

  430.     /**
  431.      * 表の見出しから、レコードのJavaクラスの定義にあるカラムの定義で初めて見つかるリストのインデックスを取得する。
  432.      * <p>カラムの定義とは、アノテーション「@XlsColumn」が付与されたもの。
  433.      * @param headers 表の見出し情報。
  434.      * @param recordClass アノテーション「@XlsColumn」が定義されたフィールドを持つレコード用のクラス。
  435.      * @param annoReader {@link AnnotationReader}
  436.      * @param config システム設定
  437.      * @return 引数「headers」の該当する要素のインデックス番号。不明な場合は0を返す。
  438.      */
  439.     private int getStartHeaderIndexForLoading(final List<RecordHeader> headers, Class<?> recordClass,
  440.             final AnnotationReader annoReader,  final Configuration config) {

  441.         // レコードクラスが不明の場合、0を返す。
  442.         if((recordClass == null || recordClass.equals(Object.class))) {
  443.             return 0;
  444.         }

  445.         for(int i=0; i < headers.size(); i++) {
  446.             RecordHeader headerInfo = headers.get(i);
  447.             final List<FieldAccessor> propeties = FieldAccessorUtils.getColumnPropertiesByName(
  448.                     recordClass, annoReader, config, headerInfo.getLabel())
  449.                     .stream()
  450.                     .filter(p -> p.isWritable())
  451.                     .collect(Collectors.toList());
  452.             if(!propeties.isEmpty()) {
  453.                 return i;
  454.             }
  455.         }

  456.         return 0;

  457.     }

  458.     private void loadMapColumns(final Sheet sheet, final List<RecordHeader> headers, final List<MergedRecord> mergedRecords,
  459.             final CellPosition beginPosition, final Class<?> recordClass, final Object record, final Configuration config, final LoadingWorkObject work) throws XlsMapperException {

  460.         final List<FieldAccessor> properties = FieldAccessorUtils.getPropertiesWithAnnotation(
  461.                 recordClass, work.getAnnoReader(), XlsMapColumns.class)
  462.                 .stream()
  463.                 .filter(p -> p.isWritable())
  464.                 .collect(Collectors.toList());

  465.         for(FieldAccessor property : properties) {
  466.             final XlsMapColumns mapAnno = property.getAnnotationNullable(XlsMapColumns.class);

  467.             if(!Utils.isLoadCase(mapAnno.cases())) {
  468.                 continue;
  469.             }

  470.             Class<?> valueClass = mapAnno.valueClass();
  471.             if(valueClass == Object.class) {
  472.                 valueClass = property.getComponentType();
  473.             }

  474.             // get converter (map key class)
  475.             final CellConverter<?> converter = getCellConverter(valueClass, property, config);
  476.             if(converter instanceof FieldFormatter) {
  477.                 work.getErrors().registerFieldFormatter(property.getName(), valueClass, (FieldFormatter<?>)converter, true);
  478.             }

  479.             boolean foundPreviousColumn = false;
  480.             final Map<String, Object> map = new LinkedHashMap<>();
  481.             for(RecordHeader headerInfo : headers){
  482.                 int hRow = beginPosition.getRow() + headerInfo.getInterval();
  483.                 if(Utils.matches(headerInfo.getLabel(), mapAnno.previousColumnName(), config)){
  484.                     foundPreviousColumn = true;
  485.                     hRow++;
  486.                     continue;
  487.                 }

  488.                 if(Utils.isNotEmpty(mapAnno.nextColumnName()) && Utils.matches(headerInfo.getLabel(), mapAnno.nextColumnName(), config)) {
  489.                     break;
  490.                 }

  491.                 if(foundPreviousColumn){
  492.                     final Cell cell = POIUtils.getCell(sheet, beginPosition.getColumn(), hRow);
  493.                     property.setMapPosition(record, CellPosition.of(cell), headerInfo.getLabel());
  494.                     property.setMapLabel(record, headerInfo.getLabel(), headerInfo.getLabel());

  495.                     property.getMapCommentSetter().ifPresent(setter ->
  496.                     config.getCommentOperator().loadMapCellComment(setter, cell, record, headerInfo.getLabel(), property, config));
  497.                    
  498.                     CellRangeAddress mergedRange = POIUtils.getMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex());
  499.                     if(mergedRange != null) {
  500.                         int mergedSize =  mergedRange.getLastColumn() - mergedRange.getFirstColumn() + 1;
  501.                         mergedRecords.add(new MergedRecord(headerInfo, mergedRange, mergedSize));
  502.                     } else {
  503.                         mergedRecords.add(new MergedRecord(headerInfo, CellRangeAddress.valueOf(POIUtils.formatCellAddress(cell)), 1));
  504.                     }

  505.                     try {
  506.                         final Object value = converter.toObject(cell);
  507.                         map.put(headerInfo.getLabel(), value);
  508.                     } catch(TypeBindException e) {
  509.                         e.setBindClass(valueClass);  // マップの項目のタイプに変更
  510.                         work.addTypeBindError(e, cell, String.format("%s[%s]", property.getName(), headerInfo.getLabel()), headerInfo.getLabel());
  511.                         if(!config.isContinueTypeBindFailure()) {
  512.                             throw e;
  513.                         }
  514.                     }
  515.                 }
  516.             }

  517.             if(foundPreviousColumn) {
  518.                 property.setValue(record, map);
  519.             }
  520.         }
  521.     }

  522.     private void loadArrayColumns(final Sheet sheet, final List<RecordHeader> headers, final List<MergedRecord> mergedRecords,
  523.             final CellPosition beginPosition, final Class<?> recordClass, final Object record, final Configuration config, final LoadingWorkObject work) throws XlsMapperException {

  524.         for(RecordHeader headerInfo : headers) {
  525.             int hRow = beginPosition.getRow() + headerInfo.getInterval();

  526.             // アノテーション「@XlsArrayColumns」の属性「columnName」と一致するプロパティを取得する。
  527.             final List<FieldAccessor> arrayProperties = FieldAccessorUtils.getArrayColumnsPropertiesByName(
  528.                     recordClass, work.getAnnoReader(), config, headerInfo.getLabel())
  529.                     .stream()
  530.                     .filter(f -> f.isWritable())
  531.                     .collect(Collectors.toList());

  532.             if(arrayProperties.isEmpty()) {
  533.                 continue;
  534.             }

  535.             for(FieldAccessor property : arrayProperties) {

  536.                 final XlsArrayColumns arrayAnno = property.getAnnotationNullable(XlsArrayColumns.class);

  537.                 if(!Utils.isLoadCase(arrayAnno.cases())) {
  538.                     continue;
  539.                 }
  540.                 Class<?> elementClass = arrayAnno.elementClass();
  541.                 if(elementClass == Object.class) {
  542.                     elementClass = property.getComponentType();
  543.                 }

  544.                 // get converter (component class)
  545.                 final CellConverter<?> converter = getCellConverter(elementClass, property, config);
  546.                 if(converter instanceof FieldFormatter) {
  547.                     work.getErrors().registerFieldFormatter(property.getName(), elementClass, (FieldFormatter<?>)converter, true);
  548.                 }

  549.                 final CellPosition initPosition = CellPosition.of(hRow, beginPosition.getColumn());

  550.                 ArrayCellsHandler arrayHandler = new ArrayCellsHandler(property, record, elementClass, sheet, config);
  551.                 arrayHandler.setLabel(headerInfo.getLabel());

  552.                 final List<Object> result = arrayHandler.handleOnLoading(arrayAnno, initPosition, converter, work, ArrayDirection.Vertical);

  553.                 if(result != null) {
  554.                     // インデックスが付いていないラベルの設定
  555.                     property.setLabel(record, headerInfo.getLabel());
  556.                 }

  557.                 final Class<?> propertyType = property.getType();
  558.                 if(Collection.class.isAssignableFrom(propertyType)) {
  559.                     if(result != null) {
  560.                         @SuppressWarnings({"unchecked", "rawtypes"})
  561.                         Collection<?> collection = Utils.convertListToCollection(result, (Class<Collection>)propertyType, config.getBeanFactory());
  562.                         property.setValue(record, collection);
  563.                     }

  564.                 } else if(propertyType.isArray()) {

  565.                     if(result != null) {
  566.                         final Object array = Array.newInstance(elementClass, result.size());
  567.                         for(int i=0; i < result.size(); i++) {
  568.                             Array.set(array, i, result.get(i));
  569.                         }
  570.                         property.setValue(record, array);
  571.                     }

  572.                 } else {
  573.                     throw new AnnotationInvalidException(arrayAnno, MessageBuilder.create("anno.notSupportType")
  574.                             .var("property", property.getNameWithClass())
  575.                             .varWithAnno("anno", XlsArrayColumns.class)
  576.                             .varWithClass("actualType", propertyType)
  577.                             .var("expectedType", "Collection(List/Set) or Array")
  578.                             .format());
  579.                 }
  580.             }
  581.         }

  582.     }

  583.     @SuppressWarnings("unchecked")
  584.     private int loadNestedRecords(final Sheet sheet, final List<RecordHeader> headers, final List<MergedRecord> mergedRecords,
  585.             final XlsVerticalRecords anno,
  586.             final CellPosition beginPosition,
  587.             final Object record,
  588.             final Configuration config, final LoadingWorkObject work) throws XlsMapperException {

  589.         // 読み飛ばす、レコード数。
  590.         // 基本的に結合している個数による。
  591.         int skipSize = 0;

  592.         final List<FieldAccessor> nestedProperties = FieldAccessorUtils.getPropertiesWithAnnotation(
  593.                 record.getClass(), work.getAnnoReader(), XlsNestedRecords.class)
  594.                 .stream()
  595.                 .filter(p -> p.isWritable())
  596.                 .collect(Collectors.toList());
  597.        
  598.         for(FieldAccessor property : nestedProperties) {

  599.             final XlsNestedRecords nestedAnno = property.getAnnotationNullable(XlsNestedRecords.class);

  600.             if(!Utils.isLoadCase(nestedAnno.cases())) {
  601.                 continue;
  602.             }

  603.             final Class<?> clazz = property.getType();
  604.             if(Collection.class.isAssignableFrom(clazz)) {
  605.                 // mapping by one-to-many

  606.                 int mergedSize = RecordsProcessorUtil.checkNestedMergedSizeRecords(sheet, mergedRecords);
  607.                 if(skipSize < mergedSize) {
  608.                     skipSize = mergedSize;
  609.                 }

  610.                 Class<?> recordClass = nestedAnno.recordClass();
  611.                 if(recordClass == Object.class) {
  612.                     recordClass = property.getComponentType();
  613.                 }

  614.                 List<?> value = loadRecords(sheet, headers, anno, beginPosition, mergedSize, property, recordClass, config, work);
  615.                 if(value != null) {
  616.                     Collection<?> collection = Utils.convertListToCollection(value, (Class<Collection>)clazz, config.getBeanFactory());
  617.                     property.setValue(record, collection);
  618.                 }

  619.             } else if(clazz.isArray()) {
  620.                 // mapping by one-to-many

  621.                 int mergedSize = RecordsProcessorUtil.checkNestedMergedSizeRecords(sheet, mergedRecords);
  622.                 if(skipSize < mergedSize) {
  623.                     skipSize = mergedSize;
  624.                 }

  625.                 Class<?> recordClass = anno.recordClass();
  626.                 if(recordClass == Object.class) {
  627.                     recordClass = property.getComponentType();
  628.                 }

  629.                 List<?> value = loadRecords(sheet, headers, anno, beginPosition, mergedSize, property, recordClass, config, work);
  630.                 if(value != null) {
  631.                     final Object array = Array.newInstance(recordClass, value.size());
  632.                     for(int i=0; i < value.size(); i++) {
  633.                         Array.set(array, i, value.get(i));
  634.                     }

  635.                     property.setValue(record, array);
  636.                 }

  637.             } else {
  638.                 // mapping by one-to-tone

  639.                 int mergedSize = 1;
  640.                 if(skipSize < mergedSize) {
  641.                     skipSize = mergedSize;
  642.                 }

  643.                 Class<?> recordClass = anno.recordClass();
  644.                 if(recordClass == Object.class) {
  645.                     recordClass = property.getType();
  646.                 }

  647.                 List<?> value = loadRecords(sheet, headers, anno, beginPosition, mergedSize, property, recordClass, config, work);
  648.                 if(value != null && !value.isEmpty()) {
  649.                     property.setValue(record, value.get(0));
  650.                 }

  651.             }
  652.         }

  653.         return skipSize;
  654.     }

  655.     /**
  656.      * レコードが有効かどうか判定する
  657.      * <p>アノテーション{@link XlsIgnorable}のメソッドで判定を行う。
  658.      * @param ignoreMethod レコードの判定を無視するかどうかの判定に使用するメソッド
  659.      * @param record 判定対象のレコードのインスタンス。
  660.      * @return trueの場合は有効。
  661.      */
  662.     private boolean isAvailabledRecord(final Optional<Method> ignoreMethod, final Object record)
  663.             throws AnnotationReadException, AnnotationInvalidException {

  664.         if(!ignoreMethod.isPresent()) {
  665.             // 判定用のメソッドが存在しない場合
  666.             return true;
  667.         }

  668.         try {
  669.             boolean ignored = (boolean)ignoreMethod.get().invoke(record);
  670.             return !ignored;

  671.         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  672.             throw new RuntimeException("fail execute method of ignoreable record", e);
  673.         }

  674.     }

  675.     @Override
  676.     public void saveProcess(final Sheet sheet, final Object beansObj, final XlsVerticalRecords anno,
  677.             final FieldAccessor accessor, final Configuration config, final SavingWorkObject work) throws XlsMapperException {

  678.         if(!accessor.isReadable()) {
  679.             // セルの値を参照するメソッド/フィールドがない場合はスキップ
  680.             return;
  681.         }
  682.        
  683.         if(!Utils.isSaveCase(anno.cases())) {
  684.             return;
  685.         }

  686.         final Class<?> clazz = accessor.getType();
  687.         final Object result = accessor.getValue(beansObj);
  688.         if(Collection.class.isAssignableFrom(clazz)) {

  689.             Class<?> recordClass = anno.recordClass();
  690.             if(recordClass == Object.class) {
  691.                 recordClass = accessor.getComponentType();
  692.             }

  693.             final Collection<Object> value = (result == null ? new ArrayList<Object>() : (Collection<Object>) result);
  694.             final List<Object> list = Utils.convertCollectionToList(value);
  695.             saveRecords(sheet, beansObj, anno, accessor, recordClass, list, config, work);

  696.         } else if(clazz.isArray()) {

  697.             Class<?> recordClass = anno.recordClass();
  698.             if(recordClass == Object.class) {
  699.                 recordClass = accessor.getComponentType();
  700.             }

  701.             final List<Object> list = Utils.asList(result, recordClass);
  702.             saveRecords(sheet, beansObj, anno, accessor, recordClass, list, config, work);

  703.         } else {
  704.             throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.notSupportType")
  705.                     .var("property", accessor.getNameWithClass())
  706.                     .varWithAnno("anno", XlsVerticalRecords.class)
  707.                     .varWithClass("actualType", clazz)
  708.                     .var("expectedType", "Collection(List/Set) or Array")
  709.                     .format());
  710.         }

  711.     }

  712.     private void saveRecords(final Sheet sheet, final Object beansObj, final XlsVerticalRecords anno, final FieldAccessor accessor,
  713.             final Class<?> recordClass, final List<Object> result,
  714.             final Configuration config, final SavingWorkObject work) throws XlsMapperException {

  715.         RecordsProcessorUtil.checkSavingNestedRecordClass(recordClass, accessor, work.getAnnoReader());

  716.         // get table starting position
  717.         final Optional<CellPosition> initPosition = getHeaderPosition(sheet, anno, accessor, config);
  718.         if(!initPosition.isPresent()) {
  719.             return;
  720.         }

  721.         // ラベルの設定
  722.         if(Utils.isNotEmpty(anno.tableLabel())) {
  723.             final Optional<Cell> tableLabelCell = CellFinder.query(sheet, anno.tableLabel(), config).findOptional();
  724.             tableLabelCell.ifPresent(c -> {
  725.                 final String label = POIUtils.getCellContents(c, config.getCellFormatter());
  726.                 accessor.setLabel(beansObj, label);

  727.             });
  728.         }

  729.         final int initColumn = initPosition.get().getColumn();
  730.         final int initRow = initPosition.get().getRow();

  731.         int hColumn = initColumn;
  732.         int hRow = initRow;

  733.         // get header columns.
  734.         final List<RecordHeader> headers = new ArrayList<>();
  735.         int rangeCount = 1;
  736.         while(true) {
  737.             try {
  738.                 Cell cell = POIUtils.getCell(sheet, hColumn, hRow);
  739.                 while(POIUtils.isEmptyCellContents(cell, config.getCellFormatter()) && rangeCount < anno.range()) {
  740.                     cell = POIUtils.getCell(sheet, hColumn, hRow + rangeCount);
  741.                     rangeCount++;
  742.                 }

  743.                 final String cellValue = POIUtils.getCellContents(cell, config.getCellFormatter());
  744.                 if(Utils.isEmpty(cellValue)) {
  745.                     break;
  746.                 }

  747.                 headers.add(new RecordHeader(cellValue, cell.getRowIndex() - initRow));
  748.                 hRow = hRow + rangeCount;
  749.                 rangeCount = 1;

  750.                 // 結合しているセルの場合は、はじめのセルだけ取得して、後は結合分スキップする。
  751.                 CellRangeAddress mergedRange = POIUtils.getMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex());
  752.                 if(mergedRange != null) {
  753.                     hRow = hRow + (mergedRange.getLastRow() - mergedRange.getFirstRow());
  754.                 }

  755.             } catch(ArrayIndexOutOfBoundsException ex) {
  756.                 break;
  757.             }

  758.             if(anno.headerLimit() > 0 && headers.size() >= anno.headerLimit()){
  759.                 break;
  760.             }
  761.         }

  762.         // レコードの操作のアノテーション
  763.         final XlsRecordOption recordOptionAnno = getRecordOptionAnnotation(accessor);

  764.         // データ行の開始位置の調整
  765.         hColumn += anno.headerRight();
  766.         CellPosition startPosition = CellPosition.of(initRow, hColumn);

  767.         // 独自の開始位置を指定する場合
  768.         final Optional<XlsRecordFinder> finderAnno = accessor.getAnnotation(XlsRecordFinder.class);
  769.         if(finderAnno.isPresent()) {
  770.             final RecordFinder finder = config.createBean(finderAnno.get().value());
  771.             startPosition = finder.find(ProcessCase.Save, finderAnno.get().args(), sheet, startPosition, beansObj, config);

  772.         }

  773.         // 書き込んだセルの範囲などの情報
  774.         final RecordOperation recordOperation = new RecordOperation(recordOptionAnno);
  775.         recordOperation.setupCellPositoin(startPosition);

  776.         // XlsColumn(merged=true)の結合したセルの情報
  777.         final List<CellRangeAddress> mergedRanges = new ArrayList<CellRangeAddress>();

  778.         saveRecords(sheet, headers,
  779.                 anno,
  780.                 startPosition, new AtomicInteger(0),
  781.                 accessor, recordClass, result,
  782.                 config, work,
  783.                 mergedRanges, recordOperation);

  784.         // 書き込むデータがない場合は、1行目の終端を操作範囲とする。
  785.         if(result.isEmpty()) {
  786.             recordOperation.setupCellPositoin(hRow-1, startPosition.getColumn());
  787.         }

  788.         if(config.isCorrectCellDataValidationOnSave()) {
  789.             correctDataValidation(sheet, recordOperation);
  790.         }

  791.         if(config.isCorrectNameRangeOnSave()) {
  792.             correctNameRange(sheet, recordOperation);
  793.         }
  794.     }

  795.     /**
  796.      * アノテーション{@link XlsRecordOption}を取得する。
  797.      * ただし、付与されていない場合は、属性にデフォルト値が指定されているものを取得する。
  798.      * @param accessor フィールド情報
  799.      * @return アノテーションのインスタンス
  800.      */
  801.     private XlsRecordOption getRecordOptionAnnotation(final FieldAccessor accessor) {

  802.         return accessor.getAnnotation(XlsRecordOption.class)
  803.                 .orElseGet(() -> new XlsRecordOption() {

  804.                     @Override
  805.                     public Class<? extends Annotation> annotationType() {
  806.                         return XlsRecordOption.class;
  807.                     }

  808.                     @Override
  809.                     public RemainedOperation remainedOperation() {
  810.                         return RemainedOperation.None;
  811.                     }

  812.                     @Override
  813.                     public OverOperation overOperation() {
  814.                         return OverOperation.Break;
  815.                     }
  816.                 });


  817.     }

  818.     private void saveRecords(final Sheet sheet, final List<RecordHeader> headers,
  819.             final XlsVerticalRecords anno,
  820.             final CellPosition initPosition, final AtomicInteger nestedRecordSize,
  821.             final FieldAccessor accessor, final Class<?> recordClass, final List<Object> result,
  822.             final Configuration config, final SavingWorkObject work,
  823.             final List<CellRangeAddress> mergedRanges, final RecordOperation recordOperation) throws XlsMapperException {

  824.         final int initColumn = initPosition.getColumn();
  825.         final int initRow = initPosition.getRow();

  826.         int hColumn = initColumn;

  827.         // Check for columns
  828.         RecordsProcessorUtil.checkColumns(sheet, recordClass, headers, work.getAnnoReader(), config);
  829.         RecordsProcessorUtil.checkMapColumns(sheet, recordClass, headers, work.getAnnoReader(), config);
  830.         RecordsProcessorUtil.checkArrayColumns(sheet, recordClass, headers, work.getAnnoReader(), config);

  831.         /*
  832.          * 書き込む時には終了位置の判定は、Borderで固定する必要がある。
  833.          * ・Emptyの場合だと、テンプレート用のシートなので必ずデータ用のセルが、空なので書き込まれなくなる。
  834.          * ・Emptyの場合、Borderに補正して書き込む。
  835.          */
  836.         RecordTerminal terminal = anno.terminal();
  837.         if(terminal == RecordTerminal.Empty) {
  838.             terminal = RecordTerminal.Border;
  839.         } else if(terminal == null){
  840.             terminal = RecordTerminal.Border;
  841.         }

  842.         // 各種レコードのコールバック用メソッドを抽出する
  843.         final RecordMethodCache methodCache = new RecordMethodFacatory(work.getAnnoReader(), config)
  844.                 .create(recordClass, ProcessCase.Save);

  845.         // レコードの見出しに対するカラム情報のキャッシュ
  846.         final Map<String, List<FieldAccessor>> propertiesCache = new HashMap<>();

  847.         // カラムに対するConverterのキャッシュ
  848.         final Map<String, CellConverter<?>> converterCache = new HashMap<>();

  849.         final int startHeaderIndex = getStartHeaderIndexForSaving(headers, recordClass, work.getAnnoReader(), config);

  850.         // get records
  851.         for(int r=0; r < POIUtils.getColumns(sheet); r++) {

  852.             boolean emptyFlag = true;

  853.             // 書き込むレコードのオブジェクトを取得。データが0件の場合、nullとなる。
  854.             final Object record;
  855.             if(r < result.size()) {
  856.                 record = result.get(r);
  857.             } else {
  858.                 record = null;
  859.             }

  860.             // パスの位置の変更
  861.             work.getErrors().pushNestedPath(accessor.getName(), r);

  862.             if(record != null) {

  863.                 // execute PreProcess listner
  864.                 methodCache.getListenerClasses().forEach(listenerClass -> {
  865.                     listenerClass.getPreSaveMethods().forEach(method -> {
  866.                         Utils.invokeNeedProcessMethod(listenerClass.getObject(), method, record, sheet, config, work.getErrors(), ProcessCase.Save);
  867.                     });
  868.                 });

  869.                 // execute PreProcess method
  870.                 methodCache.getPreSaveMethods().forEach(method -> {
  871.                     Utils.invokeNeedProcessMethod(record, method, record, sheet, config, work.getErrors(), ProcessCase.Save);
  872.                 });

  873.             }

  874. //            // レコードの各列処理で既に行を追加したかどうかのフラグ。
  875. //            boolean insertRows = false;

  876. //            // レコードの各列処理で既に行を削除したかどうかのフラグ。
  877. //            boolean deleteRows = false;


  878.             // 書き込んだセルの座標
  879.             // ネストしたときに、結合するための情報として使用する。
  880.             List<CellPosition> valueCellPositions = new ArrayList<>();

  881.             // hRowという上限がない
  882.             for(int i=0; i < headers.size(); i++) {
  883.                 final RecordHeader headerInfo = headers.get(i);
  884.                 int hRow = initRow + headerInfo.getInterval();
  885.                 final Cell cell = POIUtils.getCell(sheet, hColumn, hRow);

  886.                 // find end of the table
  887.                 if(!POIUtils.getCellContents(cell, config.getCellFormatter()).equals("")){
  888.                     emptyFlag = false;
  889.                 }

  890.                 if(terminal == RecordTerminal.Border && i == startHeaderIndex){
  891.                     final CellStyle format = cell.getCellStyle();
  892.                     if(!POIUtils.getBorderTop(cell).equals(BorderStyle.NONE)){
  893.                         emptyFlag = false;
  894.                     } else {
  895.                         emptyFlag = true;
  896. //                            break;
  897.                     }
  898.                 }

  899.                 if(!anno.terminateLabel().equals("")){
  900.                     if(Utils.matches(POIUtils.getCellContents(cell, config.getCellFormatter()), anno.terminateLabel(), config)){
  901.                         emptyFlag = true;
  902. //                            break;
  903.                     }
  904.                 }

  905.                 // mapping from Excel columns to Object properties.
  906.                 if(record != null) {
  907.                     final List<FieldAccessor> propeties = propertiesCache.computeIfAbsent(headerInfo.getLabel(), key -> {
  908.                         return FieldAccessorUtils.getColumnPropertiesByName(
  909.                                 record.getClass(), work.getAnnoReader(), config, key)
  910.                                 .stream()
  911.                                 .filter(p -> p.isReadable())
  912.                                 .collect(Collectors.toList());
  913.                     });

  914.                     for(FieldAccessor property : propeties) {
  915.                         Cell valueCell = cell;
  916.                         final XlsColumn column = property.getAnnotationNullable(XlsColumn.class);

  917.                         //TODO: マージを考慮する必要はないかも
  918.                         if(column.headerMerged() > 0) {
  919.                             hRow = hRow + column.headerMerged();
  920.                             valueCell = POIUtils.getCell(sheet, hColumn, hRow);
  921.                         }

  922.                         // for merged cell
  923.                         if(POIUtils.isEmptyCellContents(valueCell, config.getCellFormatter())) {
  924.                             if(column.merged() && POIUtils.getBorderRight(valueCell).equals(BorderStyle.NONE)){
  925.                                 for(int k=hColumn-1; k > hColumn; k--){
  926.                                     Cell tmpCell = POIUtils.getCell(sheet, k, hRow);
  927.                                     final CellStyle tmpCellFormat = tmpCell.getCellStyle();
  928.                                     if(!POIUtils.getBorderLeft(tmpCell).equals(BorderStyle.NONE)){
  929.                                         break;
  930.                                     }
  931.                                     if(!POIUtils.isEmptyCellContents(tmpCell, config.getCellFormatter())){
  932.                                         valueCell = tmpCell;
  933.                                         break;
  934.                                     }
  935.                                 }
  936.                             }
  937.                         }

  938.                         if(column.headerMerged() > 0){
  939.                             hRow = hRow - column.headerMerged();
  940.                         }

  941.                         // 書き込む行が足りない場合の操作
  942.                         if(emptyFlag) {
  943.                             if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Break)) {
  944.                                 break;

  945.                             } else if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Copy)) {
  946.                                 // 1つ左のセルの書式をコピーする。
  947.                                 final CellStyle style = POIUtils.getCell(sheet, valueCell.getColumnIndex()-1, valueCell.getRowIndex()).getCellStyle();
  948.                                 valueCell.setCellStyle(style);
  949.                                 valueCell.setBlank();

  950.                                 // セル幅の調整
  951.                                 sheet.setColumnWidth(valueCell.getColumnIndex(), sheet.getColumnWidth(valueCell.getColumnIndex()-1));

  952.                                 recordOperation.incrementCopyRecord();

  953.                             } else if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Insert)) {
  954.                                 // POIは列の追加をサポートしていないので非対応。
  955.                                 throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.attr.notSupportValue")
  956.                                         .var("property", accessor.getNameWithClass())
  957.                                         .varWithAnno("anno", XlsRecordOption.class)
  958.                                         .var("attrName", "overCase")
  959.                                         .varWithEnum("attrValue", OverOperation.Insert)
  960.                                         .format());
  961.                             }

  962.                         }

  963.                         valueCellPositions.add(CellPosition.of(valueCell));

  964.                         recordOperation.setupCellPositoin(valueCell);

  965.                         if(!Utils.isSaveCase(column.cases())) {
  966.                             continue;
  967.                         }
  968.                         // set for cell value
  969.                         property.setPosition(record, CellPosition.of(valueCell));
  970.                         property.setLabel(record, headerInfo.getLabel());
  971.                        
  972.                         final Cell tempCommentCell = valueCell;
  973.                         property.getCommentGetter().ifPresent(getter -> config.getCommentOperator().saveCellComment(
  974.                                 getter, tempCommentCell, record, accessor, config));

  975.                         final CellConverter converter = converterCache.computeIfAbsent(property.getName(), key -> getCellConverter(property, config));
  976.                         if(converter instanceof FieldFormatter) {
  977.                             work.getErrors().registerFieldFormatter(property.getName(), property.getType(), (FieldFormatter<?>)converter, true);
  978.                         }

  979.                         try {
  980.                             converter.toCell(property.getValue(record), record, sheet, CellPosition.of(valueCell));
  981.                         } catch(TypeBindException e) {
  982.                             work.addTypeBindError(e, valueCell, property.getName(), headerInfo.getLabel());
  983.                             if(!config.isContinueTypeBindFailure()) {
  984.                                 throw e;
  985.                             }
  986.                         }

  987.                         // セルをマージする
  988.                         if(column.merged() && (r > 0) && config.isMergeCellOnSave()) {
  989.                             processSavingMergedCell(valueCell, sheet, mergedRanges, config);
  990.                         }
  991.                     }
  992.                 }

  993.                 /*
  994.                  * 残りの行の操作
  995.                  *  行の追加やコピー処理をしていないときのみ実行する
  996.                  */
  997.                 if(record == null && emptyFlag == false && recordOperation.isNotExecuteOverRecordOperation()) {
  998.                     if(recordOperation.getAnnotation().remainedOperation().equals(RemainedOperation.None)) {
  999.                         // なにもしない

  1000.                     } else if(recordOperation.getAnnotation().remainedOperation().equals(RemainedOperation.Clear)) {
  1001.                         Cell clearCell = POIUtils.getCell(sheet, hColumn, hRow);
  1002.                         clearCell.setBlank();

  1003.                     } else if(recordOperation.getAnnotation().remainedOperation().equals(RemainedOperation.Delete)) {
  1004.                         // POIは列の削除をサポートしていないので非対応。
  1005.                         throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.attr.notSupportValue")
  1006.                                 .var("property", accessor.getNameWithClass())
  1007.                                 .varWithAnno("anno", XlsRecordOption.class)
  1008.                                 .var("attrName", "remainedOperation")
  1009.                                 .varWithEnum("attrValue", RemainedOperation.Delete)
  1010.                                 .format());
  1011.                     }
  1012.                 }

  1013.             }

  1014.             // マップ形式のカラムを出力する
  1015.             if(record != null) {
  1016.                 saveMapColumns(sheet, headers, valueCellPositions, CellPosition.of(initRow, hColumn), recordClass, record, terminal, anno, config, work, recordOperation);

  1017.                 saveArrayColumns(sheet, headers, valueCellPositions, CellPosition.of(initRow, hColumn), recordClass, record, terminal, anno, config, work, recordOperation);
  1018.             }

  1019.             // execute nested record.
  1020.             int skipSize = 0;
  1021.             if(record != null) {
  1022.                 skipSize = saveNestedRecords(sheet, headers, valueCellPositions, anno, CellPosition.of(initRow, hColumn), record,
  1023.                         config, work, mergedRanges, recordOperation);
  1024.                 nestedRecordSize.addAndGet(skipSize);
  1025.             }

  1026.             if(record != null) {

  1027.                 // set PostProcess listener
  1028.                 methodCache.getListenerClasses().forEach(listenerClass -> {
  1029.                     listenerClass.getPostSaveMethods().forEach(method -> {
  1030.                         work.addNeedPostProcess(new NeedProcess(record, listenerClass.getObject(), method));
  1031.                     });
  1032.                 });

  1033.                 // set PostProcess method
  1034.                 methodCache.getPostSaveMethods().forEach(method -> {
  1035.                     work.addNeedPostProcess(new NeedProcess(record, record, method));
  1036.                 });

  1037.             }

  1038.             // パスの位置の変更
  1039.             work.getErrors().popNestedPath();

  1040.             if(skipSize > 0) {
  1041.                 hColumn += skipSize;
  1042.             } else {
  1043.                 hColumn++;
  1044.             }

  1045.             if(emptyFlag == true && (r > result.size())) {
  1046.                 // セルが空で、書き込むデータがない場合。
  1047.                 break;
  1048.             }
  1049.         }

  1050.     }

  1051.     /**
  1052.      * 表の見出しから、レコードのJavaクラスの定義にあるカラムの定義で初めて見つかるリストのインデックスを取得する。
  1053.      * ・カラムの定義とは、アノテーション「@XlsColumn」が付与されたもの。
  1054.      * @param headers 表の見出し情報。
  1055.      * @param recordClass アノテーション「@XlsColumn」が定義されたフィールドを持つレコード用のクラス。
  1056.      * @param annoReader AnnotationReader
  1057.      * @param config システム設定
  1058.      * @return 引数「headers」の該当する要素のインデックス番号。不明な場合は、0を返す。
  1059.      */
  1060.     private int getStartHeaderIndexForSaving(final List<RecordHeader> headers, Class<?> recordClass,
  1061.             final AnnotationReader annoReader, final Configuration config) {

  1062.         // レコードクラスが不明の場合、0を返す。
  1063.         if((recordClass == null || recordClass.equals(Object.class))) {
  1064.             return 0;
  1065.         }

  1066.         for(int i=0; i < headers.size(); i++) {
  1067.             RecordHeader headerInfo = headers.get(i);
  1068.             final List<FieldAccessor> propeties = FieldAccessorUtils.getColumnPropertiesByName(
  1069.                     recordClass,annoReader, config,  headerInfo.getLabel())
  1070.                     .stream()
  1071.                     .filter(p -> p.isWritable())
  1072.                     .collect(Collectors.toList());
  1073.             if(!propeties.isEmpty()) {
  1074.                 return i;
  1075.             }
  1076.         }

  1077.         return 0;

  1078.     }

  1079.     /**
  1080.      * 上部のセルと同じ値の場合マージする
  1081.      * @param currentCell
  1082.      * @param sheet
  1083.      * @param mergedRanges
  1084.      * @return
  1085.      */
  1086.     private boolean processSavingMergedCell(final Cell currentCell, final Sheet sheet,
  1087.             final List<CellRangeAddress> mergedRanges, final Configuration config) {

  1088.         final int row = currentCell.getRowIndex();
  1089.         final int column = currentCell.getColumnIndex();

  1090.         if(column <= 0) {
  1091.             return false;
  1092.         }

  1093.         // 上のセルと比較する
  1094.         final String value = POIUtils.getCellContents(currentCell, config.getCellFormatter());
  1095.         String upperValue = POIUtils.getCellContents(POIUtils.getCell(sheet, column-1, row), config.getCellFormatter());

  1096.         // 結合されている場合、結合の先頭セルを取得する
  1097.         int startColumn = column - 1;
  1098.         CellRangeAddress currentMergedRange = null;
  1099.         for(CellRangeAddress range : mergedRanges) {
  1100.             // 列が範囲外の場合
  1101.             if((range.getFirstColumn() > startColumn) || (startColumn > range.getLastColumn())) {
  1102.                 continue;
  1103.             }

  1104.             // 行が範囲外の場合
  1105.             if((range.getFirstRow() > row) || (row > range.getLastRow())) {
  1106.                 continue;
  1107.             }

  1108.             upperValue = POIUtils.getCellContents(POIUtils.getCell(sheet, range.getFirstColumn(), row), config.getCellFormatter());
  1109.             currentMergedRange = range;
  1110.             break;
  1111.         }

  1112.         if(!value.equals(upperValue)) {
  1113.             // 値が異なる場合は結合しない
  1114.             return false;
  1115.         }

  1116.         // 既に結合済みの場合は一端解除する
  1117.         if(currentMergedRange != null) {
  1118.             startColumn = currentMergedRange.getFirstColumn();
  1119.             POIUtils.removeMergedRange(sheet, currentMergedRange);
  1120.         }

  1121.         final CellRangeAddress newRange = POIUtils.mergeCells(sheet, startColumn, row, column, row);
  1122.         mergedRanges.add(newRange);
  1123.         return true;

  1124.     }

  1125.     private void saveMapColumns(final Sheet sheet, final List<RecordHeader> headers, final List<CellPosition> valueCellPositions,
  1126.             final CellPosition beginPosition, final Class<?> recordClass, final Object record, final RecordTerminal terminal,
  1127.             final XlsVerticalRecords anno, final Configuration config, final SavingWorkObject work,
  1128.             final RecordOperation recordOperation) throws XlsMapperException {

  1129.         final List<FieldAccessor> properties = FieldAccessorUtils.getPropertiesWithAnnotation(
  1130.                 recordClass, work.getAnnoReader(), XlsMapColumns.class)
  1131.                 .stream()
  1132.                 .filter(p -> p.isReadable())
  1133.                 .collect(Collectors.toList());
  1134.         for(FieldAccessor property : properties) {

  1135.             final XlsMapColumns mapAnno = property.getAnnotationNullable(XlsMapColumns.class);

  1136.             Class<?> valueClass = mapAnno.valueClass();
  1137.             if(valueClass == Object.class) {
  1138.                 valueClass = property.getComponentType();
  1139.             }

  1140.             // get converter (map key class)
  1141.             final CellConverter converter = getCellConverter(valueClass, property, config);
  1142.             if(converter instanceof FieldFormatter) {
  1143.                 work.getErrors().registerFieldFormatter(property.getName(), valueClass, (FieldFormatter<?>)converter, true);
  1144.             }

  1145.             boolean foundPreviousColumn = false;
  1146.             for(RecordHeader headerInfo : headers) {
  1147.                 int hRow = beginPosition.getRow() + headerInfo.getInterval();
  1148.                 if(Utils.matches(headerInfo.getLabel(), mapAnno.previousColumnName(), config)){
  1149.                     foundPreviousColumn = true;
  1150.                     hRow++;
  1151.                     continue;
  1152.                 }

  1153.                 if(Utils.isNotEmpty(mapAnno.nextColumnName()) && Utils.matches(headerInfo.getLabel(), mapAnno.nextColumnName(), config)) {
  1154.                     break;
  1155.                 }

  1156.                 if(foundPreviousColumn) {
  1157.                     final Cell cell = POIUtils.getCell(sheet, beginPosition.getColumn(), hRow);

  1158.                     // 空セルか判断する
  1159.                     boolean emptyFlag = true;
  1160.                     if(terminal == RecordTerminal.Border) {
  1161.                         if(!POIUtils.getBorderTop(cell).equals(BorderStyle.NONE)) {
  1162.                             emptyFlag = false;
  1163.                         } else {
  1164.                             emptyFlag = true;
  1165.                         }
  1166.                     }

  1167.                     if(!anno.terminateLabel().equals("")) {
  1168.                         if(Utils.matches(POIUtils.getCellContents(cell, config.getCellFormatter()), anno.terminateLabel(), config)) {
  1169.                             emptyFlag = true;
  1170.                         }
  1171.                     }

  1172.                     // 空セルの場合
  1173.                     if(emptyFlag) {
  1174.                         if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Break)) {
  1175.                             break;

  1176.                         } else if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Copy)) {
  1177.                             final CellStyle style = POIUtils.getCell(sheet, cell.getColumnIndex()-1, cell.getRowIndex()).getCellStyle();
  1178.                             cell.setCellStyle(style);
  1179.                             cell.setBlank();

  1180.                         } else if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Insert)) {
  1181.                             // POIは列の追加をサポートしていないので非対応。
  1182.                             throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.attr.notSupportValue")
  1183.                                     .var("property", property.getNameWithClass())
  1184.                                     .varWithAnno("anno", XlsRecordOption.class)
  1185.                                     .var("attrName", "overCase")
  1186.                                     .varWithEnum("attrValue", OverOperation.Insert)
  1187.                                     .format());

  1188.                         }
  1189.                     }

  1190.                     valueCellPositions.add(CellPosition.of(cell));

  1191.                     recordOperation.setupCellPositoin(cell);

  1192.                     if(!Utils.isSaveCase(mapAnno.cases())) {
  1193.                         continue;
  1194.                     }

  1195.                     // セルの値を出力する
  1196.                     property.setMapPosition(record, CellPosition.of(cell), headerInfo.getLabel());
  1197.                     property.setMapLabel(record, headerInfo.getLabel(), headerInfo.getLabel());
  1198.                    
  1199.                     property.getMapCommentGetter().ifPresent(getter -> config.getCommentOperator().saveMapCellComment(
  1200.                             getter, cell, record, headerInfo.getLabel(), property, config));

  1201.                     try {
  1202.                         Object value = property.getValueOfMap(headerInfo.getLabel(), record);
  1203.                         converter.toCell(value, record, sheet, CellPosition.of(cell));
  1204.                     } catch(TypeBindException e) {
  1205.                         work.addTypeBindError(e, cell, String.format("%s[%s]", property.getName(), headerInfo.getLabel()), headerInfo.getLabel());
  1206.                         if(!config.isContinueTypeBindFailure()) {
  1207.                             throw e;
  1208.                         }
  1209.                     }
  1210.                 }

  1211.             }
  1212.         }

  1213.     }

  1214.     private void saveArrayColumns(final Sheet sheet, final List<RecordHeader> headers, final List<CellPosition> valueCellPositions,
  1215.             final CellPosition beginPosition, Class<?> recordClass, Object record, RecordTerminal terminal,
  1216.             XlsVerticalRecords anno, Configuration config, SavingWorkObject work,
  1217.             RecordOperation recordOperation) throws XlsMapperException {


  1218.         for(RecordHeader headerInfo : headers) {
  1219.             int hRow = beginPosition.getRow() + headerInfo.getInterval();

  1220.             // アノテーション「@XlsArrayColumns」の属性「columnName」と一致するプロパティを取得する。
  1221.             final List<FieldAccessor> arrayProperties = FieldAccessorUtils.getArrayColumnsPropertiesByName(
  1222.                     recordClass, work.getAnnoReader(), config, headerInfo.getLabel())
  1223.                     .stream()
  1224.                     .filter(f -> f.isReadable())
  1225.                     .collect(Collectors.toList());

  1226.             if(arrayProperties.isEmpty()) {
  1227.                 continue;
  1228.             }

  1229.             for(FieldAccessor property : arrayProperties) {

  1230.                 final XlsArrayColumns arrayAnno = property.getAnnotationNullable(XlsArrayColumns.class);

  1231.                 Class<?> elementClass = arrayAnno.elementClass();
  1232.                 if(elementClass == Object.class) {
  1233.                     elementClass = property.getComponentType();
  1234.                 }
  1235.                 final CellPosition initPosition = CellPosition.of(hRow, beginPosition.getColumn());

  1236.                 // 書き込む領域について、上のセルをコピーなどする。
  1237.                 int iRow = initPosition.getRow();
  1238.                 for(int i=0; i < arrayAnno.size(); i++) {
  1239.                     final Cell cell = POIUtils.getCell(sheet, initPosition.getColumn(), iRow);

  1240.                     // 空セルか判断する - 値のセルかどうか
  1241.                     boolean emptyFlag = true;

  1242.                     if(terminal == RecordTerminal.Border) {
  1243.                         if(!POIUtils.getBorderTop(cell).equals(BorderStyle.NONE)) {
  1244.                             emptyFlag = false;
  1245.                         } else {
  1246.                             emptyFlag = true;
  1247.                         }
  1248.                     }

  1249.                     if(!anno.terminateLabel().equals("")) {
  1250.                         if(Utils.matches(POIUtils.getCellContents(cell, config.getCellFormatter()), anno.terminateLabel(), config)) {
  1251.                             emptyFlag = true;
  1252.                         }
  1253.                     }

  1254.                     // 空セルの場合
  1255.                     if(emptyFlag) {
  1256.                         if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Break)) {
  1257.                             break;

  1258.                         } else if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Copy)) {
  1259.                             final Cell fromCell = POIUtils.getCell(sheet, cell.getColumnIndex()-1, cell.getRowIndex());
  1260.                             copyCellStyle(fromCell, cell);

  1261.                         } else if(recordOperation.getAnnotation().overOperation().equals(OverOperation.Insert)) {
  1262.                             // POIは列の追加をサポートしていないので非対応。
  1263.                             throw new AnnotationInvalidException(anno, MessageBuilder.create("anno.attr.notSupportValue")
  1264.                                     .var("property", property.getNameWithClass())
  1265.                                     .varWithAnno("anno", XlsRecordOption.class)
  1266.                                     .var("attrName", "overCase")
  1267.                                     .varWithEnum("attrValue", OverOperation.Insert)
  1268.                                     .format());


  1269.                         }
  1270.                     }

  1271.                     // 結合情報を考慮して、インデックス(列番号)を次のセルに進める。
  1272.                     if(arrayAnno.elementMerged()) {
  1273.                         final CellRangeAddress mergedRegion = POIUtils.getMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex());
  1274.                         if(mergedRegion != null) {
  1275.                             iRow += POIUtils.getRowSize(mergedRegion);
  1276.                         } else {
  1277.                             iRow++;
  1278.                         }

  1279.                     } else {
  1280.                         iRow++;
  1281.                     }

  1282.                     recordOperation.setupCellPositoin(cell);
  1283.                 }

  1284.                 if(!Utils.isSaveCase(arrayAnno.cases())) {
  1285.                     continue;
  1286.                 }

  1287.                 // get converter (component class)
  1288.                 final CellConverter<?> converter = getCellConverter(elementClass, property, config);
  1289.                 if(converter instanceof FieldFormatter) {
  1290.                     work.getErrors().registerFieldFormatter(property.getName(), elementClass, (FieldFormatter<?>)converter, true);
  1291.                 }

  1292.                 ArrayCellsHandler arrayHandler = new ArrayCellsHandler(property, record, elementClass, sheet, config);
  1293.                 arrayHandler.setLabel(headerInfo.getLabel());

  1294.                 final Class<?> propertyType = property.getType();
  1295.                 final Object result = property.getValue(record);

  1296.                 if(result != null) {
  1297.                     // インデックスが付いていないラベルの設定
  1298.                     property.setLabel(record, headerInfo.getLabel());
  1299.                 }

  1300.                 if(Collection.class.isAssignableFrom(propertyType)) {

  1301.                     final Collection<Object> value = (result == null ? new ArrayList<Object>() : (Collection<Object>) result);
  1302.                     final List<Object> list = Utils.convertCollectionToList(value);
  1303.                     arrayHandler.handleOnSaving(list, arrayAnno, initPosition, converter, work, ArrayDirection.Vertical);

  1304.                 } else if(propertyType.isArray()) {

  1305.                     final List<Object> list = Utils.asList(result, elementClass);
  1306.                     arrayHandler.handleOnSaving(list, arrayAnno, initPosition, converter, work, ArrayDirection.Vertical);
  1307.                 }

  1308.             }
  1309.         }

  1310.     }

  1311.     /**
  1312.      * セルの書式をコピーする。
  1313.      * <p>コピー先のセルの種類は、空セルとする。</p>
  1314.      * <p>結合情報も列方向の結合をコピーする。</p>
  1315.      *
  1316.      * @since 2.0
  1317.      * @param fromCell コピー元
  1318.      * @param toCell コピー先
  1319.      */
  1320.     private void copyCellStyle(final Cell fromCell, final Cell toCell) {

  1321.         final CellStyle style = fromCell.getCellStyle();
  1322.         toCell.setCellStyle(style);
  1323.         toCell.setBlank();

  1324.         // 縦方向に結合されている場合、結合情報のコピーする。(XlsArrayColumns用)
  1325.         final Sheet sheet = fromCell.getSheet();
  1326.         final CellRangeAddress mergedRegion = POIUtils.getMergedRegion(sheet, fromCell.getRowIndex(), fromCell.getColumnIndex());
  1327.         final int mergedSize = POIUtils.getRowSize(mergedRegion);

  1328.         if(mergedSize >= 2) {
  1329.             CellRangeAddress newMergedRegion = POIUtils.getMergedRegion(sheet, toCell.getRowIndex(), toCell.getColumnIndex());
  1330.             if(newMergedRegion != null) {
  1331.                 // 既に結合している場合 - 通常はありえない。
  1332.                 return;
  1333.             }

  1334.             newMergedRegion = POIUtils.mergeCells(sheet,
  1335.                     toCell.getColumnIndex(), mergedRegion.getFirstRow(), toCell.getColumnIndex(), mergedRegion.getLastRow());

  1336.             // 結合先のセルの書式も設定する
  1337.             for(int i=1; i < mergedSize; i++) {
  1338.                 Cell mergedFromCell = POIUtils.getCell(sheet, fromCell.getColumnIndex(), toCell.getRowIndex()+i);

  1339.                 Cell mergedToCell = POIUtils.getCell(sheet, toCell.getColumnIndex(), toCell.getRowIndex()+i);
  1340.                 mergedToCell.setCellStyle(mergedFromCell.getCellStyle());
  1341.                 mergedToCell.setBlank();
  1342.             }
  1343.         }

  1344.     }

  1345.     @SuppressWarnings("unchecked")
  1346.     private int saveNestedRecords(final Sheet sheet, final List<RecordHeader> headers, final List<CellPosition> valueCellPositions,
  1347.             final XlsVerticalRecords anno,
  1348.             final CellPosition beginPositoin,
  1349.             final Object record,
  1350.             final Configuration config, final SavingWorkObject work,
  1351.             final List<CellRangeAddress> mergedRanges, final RecordOperation recordOperation) throws XlsMapperException {

  1352.         int skipSize = 0;

  1353.         final List<FieldAccessor> nestedProperties = FieldAccessorUtils.getPropertiesWithAnnotation(
  1354.                 record.getClass(), work.getAnnoReader(), XlsNestedRecords.class)
  1355.                 .stream()
  1356.                 .filter(p -> p.isReadable())
  1357.                 .collect(Collectors.toList());
  1358.        
  1359.         for(FieldAccessor property : nestedProperties) {

  1360.             final XlsNestedRecords nestedAnno = property.getAnnotationNullable(XlsNestedRecords.class);

  1361.             if(!Utils.isSaveCase(nestedAnno.cases())) {
  1362.                 continue;
  1363.             }

  1364.             final Class<?> clazz = property.getType();
  1365.             if(Collection.class.isAssignableFrom(clazz)) {
  1366.                 // mapping by one-to-many

  1367.                 Class<?> recordClass = nestedAnno.recordClass();
  1368.                 if(recordClass == Object.class) {
  1369.                     recordClass = property.getComponentType();
  1370.                 }

  1371.                 Collection<Object> value = (Collection<Object>) property.getValue(record);
  1372.                 if(value == null) {
  1373.                     // dummy empty record
  1374.                     value = (Collection<Object>) Arrays.asList(config.createBean(recordClass));
  1375.                 }

  1376.                 final List<Object> list = Utils.convertCollectionToList(value);
  1377.                 final AtomicInteger nestedRecordSize = new AtomicInteger(0);
  1378.                 saveRecords(sheet, headers, anno, beginPositoin, nestedRecordSize, property, recordClass, list,
  1379.                         config, work, mergedRanges, recordOperation);

  1380.                 if(skipSize < list.size()) {
  1381.                     if(nestedRecordSize.get() > 0) {
  1382.                         skipSize = nestedRecordSize.get() - skipSize;
  1383.                     } else {
  1384.                         skipSize = list.size();
  1385.                     }
  1386.                 }

  1387.                 processSavingNestedMergedRecord(sheet, skipSize, valueCellPositions);

  1388.             } else if(clazz.isArray()) {

  1389.                 // mapping by one-to-many

  1390.                 Class<?> recordClass = nestedAnno.recordClass();
  1391.                 if(recordClass == Object.class) {
  1392.                     recordClass = property.getComponentType();
  1393.                 }

  1394.                 Object[] value = (Object[])property.getValue(record);
  1395.                 if(value == null) {
  1396.                     // dummy empty record
  1397.                     value = new Object[]{config.createBean(recordClass)};
  1398.                 }

  1399.                 final List<Object> list = Arrays.asList(value);
  1400.                 final AtomicInteger nestedRecordSize = new AtomicInteger(0);
  1401.                 saveRecords(sheet, headers, anno, beginPositoin, nestedRecordSize, property, recordClass, list,
  1402.                         config, work, mergedRanges, recordOperation);

  1403.                 if(nestedRecordSize.get() > 0) {
  1404.                     skipSize = nestedRecordSize.get() - skipSize;
  1405.                 } else {
  1406.                     skipSize = list.size();
  1407.                 }

  1408.                 processSavingNestedMergedRecord(sheet, skipSize, valueCellPositions);

  1409.             } else {

  1410.                 // mapping by one-to-many
  1411.                 Class<?> recordClass = anno.recordClass();
  1412.                 if(recordClass == Object.class) {
  1413.                     recordClass = property.getType();
  1414.                 }

  1415.                 Object value = property.getValue(record);
  1416.                 if(value == null) {
  1417.                     // dummy empty record
  1418.                     value = config.createBean(recordClass);
  1419.                 }

  1420.                 List<Object> list = Arrays.asList(value);
  1421.                 final AtomicInteger nestedRecordSize = new AtomicInteger(0);
  1422.                 saveRecords(sheet, headers, anno, beginPositoin, nestedRecordSize, property, recordClass, list,
  1423.                         config, work, mergedRanges, recordOperation);

  1424.                 if(nestedRecordSize.get() > 0) {
  1425.                     skipSize = nestedRecordSize.get() - skipSize;
  1426.                 } else {
  1427.                     skipSize = list.size();
  1428.                 }

  1429.             }
  1430.         }

  1431.         return skipSize;
  1432.     }

  1433.     /**
  1434.      * ネストしたレコードの親のセルを結合する
  1435.      * @param sheet シート
  1436.      * @param mergedSize 結合するセルのサイズ
  1437.      * @param valueCellPositions 結合する開始位置のセルのアドレス
  1438.      */
  1439.     private void processSavingNestedMergedRecord(final Sheet sheet, final int mergedSize,
  1440.             final List<CellPosition> valueCellPositions) {

  1441.         if(mergedSize <= 1) {
  1442.             return;
  1443.         }

  1444.         // ネストした場合、上のセルのスタイルをコピーして、結合する
  1445.         for(CellPosition position : valueCellPositions) {
  1446.             Cell valueCell = POIUtils.getCell(sheet, position);
  1447.             if(valueCell == null) {
  1448.                 continue;
  1449.             }

  1450.             final CellStyle style = valueCell.getCellStyle();

  1451.             // 結合するセルに対して、上のセルのスタイルをコピーする。
  1452.             // 列を挿入するときなどに必要になるため、スタイルを設定する。
  1453.             for(int i=1; i < mergedSize; i++) {
  1454.                 Cell mergedCell = POIUtils.getCell(sheet, position.getColumn() + i, position.getRow());
  1455.                 mergedCell.setCellStyle(style);
  1456.                 mergedCell.setBlank();
  1457.             }

  1458.             final CellRangeAddress range = new CellRangeAddress(position.getRow(), position.getRow(),
  1459.                     position.getColumn(), position.getColumn() + mergedSize -1);

  1460.             // 既に結合済みのセルがある場合、外す。
  1461.             for(int colIdx=range.getFirstColumn(); colIdx <= range.getLastColumn(); colIdx++) {
  1462.                 CellRangeAddress r = POIUtils.getMergedRegion(sheet, position.getRow(), colIdx);
  1463.                 if(r != null) {
  1464.                     POIUtils.removeMergedRange(sheet, r);
  1465.                 }
  1466.             }

  1467.             sheet.addMergedRegion(range);
  1468.         }

  1469.     }

  1470.     /**
  1471.      * セルの入力規則の範囲を修正する。
  1472.      * @param sheet
  1473.      * @param recordOperation
  1474.      */
  1475.     private void correctDataValidation(final Sheet sheet, final RecordOperation recordOperation) {

  1476.         if(recordOperation.isNotExecuteRecordOperation()) {
  1477.             return;
  1478.         }

  1479.         //TODO: セルの結合も考慮する

  1480.         // 操作をしていないセルの範囲の取得
  1481.         final CellRangeAddress notOperateRange = new CellRangeAddress(
  1482.                 recordOperation.getTopLeftPoisitoin().y,
  1483.                 recordOperation.getBottomRightPosition().y,
  1484.                 recordOperation.getTopLeftPoisitoin().x,
  1485.                 recordOperation.getBottomRightPosition().x - recordOperation.getCountInsertRecord()
  1486.                 );

  1487.         final List<? extends DataValidation> list = sheet.getDataValidations();
  1488.         for(DataValidation validation : list) {

  1489.             final CellRangeAddressList region = validation.getRegions().copy();
  1490.             boolean changedRange = false;
  1491.             for(CellRangeAddress range : region.getCellRangeAddresses()) {

  1492.                 if(notOperateRange.isInRange(range.getFirstRow(), range.getFirstColumn())) {
  1493.                     // 自身のセルの範囲の場合は、行の範囲を広げる
  1494.                     range.setLastColumn(recordOperation.getBottomRightPosition().x);
  1495.                     changedRange = true;

  1496.                 } else if(notOperateRange.getLastColumn() < range.getFirstColumn()) {
  1497.                     /*
  1498.                      * VerticalRecordsの場合は、挿入・削除はないので、自身以外の範囲は修正しない。
  1499.                      */
  1500.                 }

  1501.             }

  1502.             // 修正した規則を、再度シートに追加する
  1503.             if(changedRange) {
  1504.                 boolean updated = POIUtils.updateDataValidationRegion(sheet, validation.getRegions(), region);
  1505.                 assert updated == true;
  1506.             }
  1507.         }

  1508.     }

  1509.     /**
  1510.      * 名前の定義の範囲を修正する。
  1511.      * @param sheet
  1512.      * @param recordOperation
  1513.      */
  1514.     private void correctNameRange(final Sheet sheet, final RecordOperation recordOperation) {

  1515.         if(recordOperation.isNotExecuteRecordOperation()) {
  1516.             return;
  1517.         }

  1518.         final Workbook workbook = sheet.getWorkbook();
  1519.         final int numName = workbook.getNumberOfNames();
  1520.         if(numName == 0) {
  1521.             return;
  1522.         }

  1523.         // 操作をしていないセルの範囲の取得
  1524.         final CellRangeAddress notOperateRange = new CellRangeAddress(
  1525.                 recordOperation.getTopLeftPoisitoin().y,
  1526.                 recordOperation.getBottomRightPosition().y,
  1527.                 recordOperation.getTopLeftPoisitoin().x,
  1528.                 recordOperation.getBottomRightPosition().x - recordOperation.getCountInsertRecord()
  1529.                 );

  1530.         for(Name name : workbook.getAllNames()) {

  1531.             if(name.isDeleted() || name.isFunctionName()) {
  1532.                 // 削除されている場合、関数の場合はスキップ
  1533.                 continue;
  1534.             }

  1535.             if(!sheet.getSheetName().equals(name.getSheetName())) {
  1536.                 // 自身のシートでない名前は、修正しない。
  1537.                 continue;
  1538.             }

  1539.             AreaReference areaRef = new AreaReference(name.getRefersToFormula(), POIUtils.getVersion(sheet));
  1540.             CellReference firstCellRef = areaRef.getFirstCell();
  1541.             CellReference lastCellRef = areaRef.getLastCell();

  1542.             if(notOperateRange.isInRange(firstCellRef.getRow(), firstCellRef.getCol())) {
  1543.                 // 自身のセルの範囲の場合は、行の範囲を広げる。

  1544.                 lastCellRef= new CellReference(
  1545.                         lastCellRef.getSheetName(),
  1546.                         lastCellRef.getRow(), recordOperation.getBottomRightPosition().x,
  1547.                         lastCellRef.isRowAbsolute(), lastCellRef.isColAbsolute());
  1548.                 areaRef = new AreaReference(firstCellRef, lastCellRef, sheet.getWorkbook().getSpreadsheetVersion());

  1549.                 // 修正した範囲を再設定する
  1550.                 name.setRefersToFormula(areaRef.formatAsString());

  1551.             } else if(notOperateRange.getLastColumn() < firstCellRef.getCol()) {
  1552.                 /*
  1553.                  * 名前の定義の場合、自身のセルノ範囲より右方にあるセルの範囲の場合、
  1554.                  * 自動的に修正されるため、修正は必要なし。
  1555.                  */

  1556.             }

  1557.         }

  1558.     }

  1559. }