1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <xepivotxml.hxx>
#include <dpcache.hxx>
#include <dpdimsave.hxx>
#include <dpitemdata.hxx>
#include <dpobject.hxx>
#include <dpsave.hxx>
#include <dputil.hxx>
#include <document.hxx>
#include <generalfunction.hxx>
#include <unonames.hxx>
#include <xestyle.hxx>
#include <xeroot.hxx>

#include <o3tl/temporary.hxx>
#include <o3tl/safeint.hxx>
#include <oox/export/utils.hxx>
#include <oox/token/namespaces.hxx>
#include <sax/tools/converter.hxx>
#include <sax/fastattribs.hxx>

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sheet/DataPilotFieldGroupBy.hpp>
#include <com/sun/star/sheet/DataPilotFieldOrientation.hpp>
#include <com/sun/star/sheet/DataPilotFieldLayoutMode.hpp>
#include <com/sun/star/sheet/DataPilotOutputRangeType.hpp>
#include <com/sun/star/sheet/XDimensionsSupplier.hpp>

#include <vector>

using namespace oox;
using namespace com::sun::star;

namespace {

void savePivotCacheRecordsXml( XclExpXmlStream& rStrm, const ScDPCache& rCache )
{
    SCROW nCount = rCache.GetDataSize();
    size_t nFieldCount = rCache.GetFieldCount();

    sax_fastparser::FSHelperPtr& pRecStrm = rStrm.GetCurrentStream();
    pRecStrm->startElement(XML_pivotCacheRecords,
        XML_xmlns, rStrm.getNamespaceURL(OOX_NS(xls)).toUtf8(),
        FSNS(XML_xmlns, XML_r), rStrm.getNamespaceURL(OOX_NS(officeRel)).toUtf8(),
        XML_count, OString::number(static_cast<long>(nCount)));

    for (SCROW i = 0; i < nCount; ++i)
    {
        pRecStrm->startElement(XML_r);
        for (size_t nField = 0; nField < nFieldCount; ++nField)
        {
            const ScDPCache::IndexArrayType* pArray = rCache.GetFieldIndexArray(nField);
            assert(pArray);
            assert(o3tl::make_unsigned(i) < pArray->size());

            // We are using XML_x reference (like: <x v="0"/>), instead of values here (eg: <s v="No Discount"/>).
            // That's why in SavePivotCacheXml method, we need to list all items.
            pRecStrm->singleElement(XML_x, XML_v, OString::number((*pArray)[i]));
        }
        pRecStrm->endElement(XML_r);
    }

    pRecStrm->endElement(XML_pivotCacheRecords);
}

const char* toOOXMLAxisType( sheet::DataPilotFieldOrientation eOrient )
{
    switch (eOrient)
    {
        case sheet::DataPilotFieldOrientation_COLUMN:
            return "axisCol";
        case sheet::DataPilotFieldOrientation_ROW:
            return "axisRow";
        case sheet::DataPilotFieldOrientation_PAGE:
            return "axisPage";
        case sheet::DataPilotFieldOrientation_DATA:
            return "axisValues";
        case sheet::DataPilotFieldOrientation_HIDDEN:
        default:
            ;
    }

    return "";
}

const char* toOOXMLSubtotalType(ScGeneralFunction eFunc)
{
    switch (eFunc)
    {
        case ScGeneralFunction::SUM:
            return "sum";
        case ScGeneralFunction::COUNT:
            return "count";
        case ScGeneralFunction::AVERAGE:
            return "average";
        case ScGeneralFunction::MAX:
            return "max";
        case ScGeneralFunction::MIN:
            return "min";
        case ScGeneralFunction::PRODUCT:
            return "product";
        case ScGeneralFunction::COUNTNUMS:
            return "countNums";
        case ScGeneralFunction::STDEV:
            return "stdDev";
        case ScGeneralFunction::STDEVP:
            return "stdDevp";
        case ScGeneralFunction::VAR:
            return "var";
        case ScGeneralFunction::VARP:
            return "varp";
        default:
            ;
    }
    return nullptr;
}

}

XclExpXmlPivotCaches::XclExpXmlPivotCaches( const XclExpRoot& rRoot ) :
    XclExpRoot(rRoot) {}

void XclExpXmlPivotCaches::SaveXml( XclExpXmlStream& rStrm )
{
    sax_fastparser::FSHelperPtr& pWorkbookStrm = rStrm.GetCurrentStream();
    pWorkbookStrm->startElement(XML_pivotCaches);

    for (size_t i = 0, n = maCaches.size(); i < n; ++i)
    {
        const Entry& rEntry = maCaches[i];

        sal_Int32 nCacheId = i + 1;
        OUString aRelId;
        sax_fastparser::FSHelperPtr pPCStrm = rStrm.CreateOutputStream(
            XclXmlUtils::GetStreamName("xl/pivotCache/", "pivotCacheDefinition", nCacheId),
            XclXmlUtils::GetStreamName(nullptr, "pivotCache/pivotCacheDefinition", nCacheId),
            rStrm.GetCurrentStream()->getOutputStream(),
            CREATE_XL_CONTENT_TYPE("pivotCacheDefinition"),
            CREATE_OFFICEDOC_RELATION_TYPE("pivotCacheDefinition"),
            &aRelId);

        pWorkbookStrm->singleElement(XML_pivotCache,
            XML_cacheId, OString::number(nCacheId),
            FSNS(XML_r, XML_id), aRelId.toUtf8());

        rStrm.PushStream(pPCStrm);
        SavePivotCacheXml(rStrm, rEntry, nCacheId);
        rStrm.PopStream();
    }

    pWorkbookStrm->endElement(XML_pivotCaches);
}

void XclExpXmlPivotCaches::SetCaches( const std::vector<Entry>& rCaches )
{
    maCaches = rCaches;
}

bool XclExpXmlPivotCaches::HasCaches() const
{
    return !maCaches.empty();
}

const XclExpXmlPivotCaches::Entry* XclExpXmlPivotCaches::GetCache( sal_Int32 nCacheId ) const
{
    if (nCacheId <= 0)
        // cache ID is 1-based.
        return nullptr;

    size_t nPos = nCacheId - 1;
    if (nPos >= maCaches.size())
        return nullptr;

    return &maCaches[nPos];
}

namespace {
/**
 * Create combined date and time string according the requirements of Excel.
 * A single point in time can be represented by concatenating a complete date expression,
 * the letter T as a delimiter, and a valid time expression. For example, "2007-04-05T14:30".
 *
 * fSerialDateTime - a number representing the number of days since 1900-Jan-0 (integer portion of the number),
 * plus a fractional portion of a 24 hour day (fractional portion of the number).
 */
OUString GetExcelFormattedDate( double fSerialDateTime, const SvNumberFormatter& rFormatter )
{
    // tdf#125055: properly round the value to seconds when truncating nanoseconds below
    constexpr double fHalfSecond = 1 / 86400.0 * 0.5;
    css::util::DateTime aUDateTime
        = (DateTime(rFormatter.GetNullDate()) + fSerialDateTime + fHalfSecond).GetUNODateTime();
    // We need to reset nanoseconds, to avoid string like: "1982-02-18T16:04:47.999999849"
    aUDateTime.NanoSeconds = 0;
    OUStringBuffer sBuf;
    ::sax::Converter::convertDateTime(sBuf, aUDateTime, nullptr, true);
    return sBuf.makeStringAndClear();
}

// Excel seems to expect different order of group item values; we need to rearrange elements
// to output "<date1" first, then elements, then ">date2" last.
// Since ScDPItemData::DateFirst is -1, ScDPItemData::DateLast is 10000, and other date group
// items would fit between those in order (like 0 = Jan, 1 = Feb, etc.), we can simply sort
// the items by value.
std::vector<OUString> SortGroupItems(const ScDPCache& rCache, long nDim)
{
    struct ItemData
    {
        sal_Int32 nVal;
        const ScDPItemData* pData;
    };
    std::vector<ItemData> aDataToSort;
    ScfInt32Vec aGIIds;
    rCache.GetGroupDimMemberIds(nDim, aGIIds);
    for (sal_Int32 id : aGIIds)
    {
        const ScDPItemData* pGIData = rCache.GetItemDataById(nDim, id);
        if (pGIData->GetType() == ScDPItemData::GroupValue)
        {
            auto aGroupVal = pGIData->GetGroupValue();
            aDataToSort.push_back({ aGroupVal.mnValue, pGIData });
        }
    }
    std::sort(aDataToSort.begin(), aDataToSort.end(),
              [](const ItemData& a, const ItemData& b) { return a.nVal < b.nVal; });

    std::vector<OUString> aSortedResult;
    for (const auto& el : aDataToSort)
    {
        aSortedResult.push_back(rCache.GetFormattedString(nDim, *el.pData, false));<--- Consider using std::transform algorithm instead of a raw loop.
    }
    return aSortedResult;
}
} // namespace

void XclExpXmlPivotCaches::SavePivotCacheXml( XclExpXmlStream& rStrm, const Entry& rEntry, sal_Int32 nCounter )
{
    assert(rEntry.mpCache);
    const ScDPCache& rCache = *rEntry.mpCache;

    sax_fastparser::FSHelperPtr& pDefStrm = rStrm.GetCurrentStream();

    OUString aRelId;
    sax_fastparser::FSHelperPtr pRecStrm = rStrm.CreateOutputStream(
        XclXmlUtils::GetStreamName("xl/pivotCache/", "pivotCacheRecords", nCounter),
        XclXmlUtils::GetStreamName(nullptr, "pivotCacheRecords", nCounter),
        pDefStrm->getOutputStream(),
        CREATE_XL_CONTENT_TYPE("pivotCacheRecords"),
        CREATE_OFFICEDOC_RELATION_TYPE("pivotCacheRecords"),
        &aRelId);

    rStrm.PushStream(pRecStrm);
    savePivotCacheRecordsXml(rStrm, rCache);
    rStrm.PopStream();

    pDefStrm->startElement(XML_pivotCacheDefinition,
        XML_xmlns, rStrm.getNamespaceURL(OOX_NS(xls)).toUtf8(),
        FSNS(XML_xmlns, XML_r), rStrm.getNamespaceURL(OOX_NS(officeRel)).toUtf8(),
        FSNS(XML_r, XML_id), aRelId.toUtf8(),
        XML_recordCount, OString::number(rEntry.mpCache->GetDataSize()),
        XML_createdVersion, "3"); // MS Excel 2007, tdf#112936: setting version number makes MSO to handle the pivot table differently

    pDefStrm->startElement(XML_cacheSource, XML_type, "worksheet");

    OUString aSheetName;
    GetDoc().GetName(rEntry.maSrcRange.aStart.Tab(), aSheetName);
    pDefStrm->singleElement(XML_worksheetSource,
        XML_ref, XclXmlUtils::ToOString(rStrm.GetRoot().GetDoc(), rEntry.maSrcRange),
        XML_sheet, aSheetName.toUtf8());

    pDefStrm->endElement(XML_cacheSource);

    size_t nCount = rCache.GetFieldCount();
    const size_t nGroupFieldCount = rCache.GetGroupFieldCount();
    pDefStrm->startElement(XML_cacheFields,
        XML_count, OString::number(static_cast<long>(nCount + nGroupFieldCount)));

    auto WriteFieldGroup = [this, &rCache, pDefStrm](size_t i, size_t base) {
        const sal_Int32 nDatePart = rCache.GetGroupType(i);
        if (!nDatePart)
            return;
        OString sGroupBy;
        switch (nDatePart)
        {
        case sheet::DataPilotFieldGroupBy::SECONDS:
            sGroupBy = "seconds";
            break;
        case sheet::DataPilotFieldGroupBy::MINUTES:
            sGroupBy = "minutes";
            break;
        case sheet::DataPilotFieldGroupBy::HOURS:
            sGroupBy = "hours";
            break;
        case sheet::DataPilotFieldGroupBy::DAYS:
            sGroupBy = "days";
            break;
        case sheet::DataPilotFieldGroupBy::MONTHS:
            sGroupBy = "months";
            break;
        case sheet::DataPilotFieldGroupBy::QUARTERS:
            sGroupBy = "quarters";
            break;
        case sheet::DataPilotFieldGroupBy::YEARS:
            sGroupBy = "years";
            break;
        }

        // fieldGroup element
        pDefStrm->startElement(XML_fieldGroup, XML_base, OString::number(base));

        SvNumberFormatter& rFormatter = GetFormatter();<--- Variable 'rFormatter' can be declared with const

        // rangePr element
        const ScDPNumGroupInfo* pGI = rCache.GetNumGroupInfo(i);
        auto pGroupAttList = sax_fastparser::FastSerializerHelper::createAttrList();
        pGroupAttList->add(XML_groupBy, sGroupBy);
        // Possible TODO: find out when to write autoStart attribute for years grouping
        pGroupAttList->add(XML_startDate, GetExcelFormattedDate(pGI->mfStart, rFormatter).toUtf8());
        pGroupAttList->add(XML_endDate, GetExcelFormattedDate(pGI->mfEnd, rFormatter).toUtf8());
        if (pGI->mfStep)
            pGroupAttList->add(XML_groupInterval, OString::number(pGI->mfStep));
        pDefStrm->singleElement(XML_rangePr, pGroupAttList);

        // groupItems element
        auto aElemVec = SortGroupItems(rCache, i);
        pDefStrm->startElement(XML_groupItems, XML_count, OString::number(aElemVec.size()));
        for (const auto& sElem : aElemVec)
        {
            pDefStrm->singleElement(XML_s, XML_v, sElem.toUtf8());
        }
        pDefStrm->endElement(XML_groupItems);
        pDefStrm->endElement(XML_fieldGroup);
    };

    for (size_t i = 0; i < nCount; ++i)
    {
        OUString aName = rCache.GetDimensionName(i);

        pDefStrm->startElement(XML_cacheField,
            XML_name, aName.toUtf8(),
            XML_numFmtId, OString::number(0));

        const ScDPCache::ScDPItemDataVec& rFieldItems = rCache.GetDimMemberValues(i);

        std::set<ScDPItemData::Type> aDPTypes;
        double fMin = std::numeric_limits<double>::infinity(), fMax = -std::numeric_limits<double>::infinity();
        bool isValueInteger = true;
        bool isContainsDate = rCache.IsDateDimension(i);
        bool isLongText = false;
        for (const auto& rFieldItem : rFieldItems)
        {
            ScDPItemData::Type eType = rFieldItem.GetType();
            // tdf#123939 : error and string are same for cache; if both are present, keep only one
            if (eType == ScDPItemData::Error)
                eType = ScDPItemData::String;
            aDPTypes.insert(eType);
            if (eType == ScDPItemData::Value)
            {
                double fVal = rFieldItem.GetValue();
                fMin = std::min(fMin, fVal);
                fMax = std::max(fMax, fVal);

                // Check if all values are integers
                if (isValueInteger && (modf(fVal, &o3tl::temporary(double())) != 0.0))
                {
                    isValueInteger = false;
                }
            }
            else if (eType == ScDPItemData::String && !isLongText)
            {
                isLongText = rFieldItem.GetString().getLength() > 255;
            }
        }

        auto pAttList = sax_fastparser::FastSerializerHelper::createAttrList();
        // TODO In same cases, disable listing of items, as it is done in MS Excel.
        // Exporting savePivotCacheRecordsXml method needs to be updated accordingly
        //bool bListItems = true;

        std::set<ScDPItemData::Type> aDPTypesWithoutBlank = aDPTypes;
        aDPTypesWithoutBlank.erase(ScDPItemData::Empty);

        const bool isContainsString = aDPTypesWithoutBlank.count(ScDPItemData::String) > 0;
        const bool isContainsBlank = aDPTypes.count(ScDPItemData::Empty) > 0;
        const bool isContainsNumber
            = !isContainsDate && aDPTypesWithoutBlank.count(ScDPItemData::Value) > 0;
        bool isContainsNonDate = !(isContainsDate && aDPTypesWithoutBlank.size() <= 1);

        // XML_containsSemiMixedTypes possible values:
        // 1 - (Default) at least one text value, or can also contain a mix of other data types and blank values,
        //     or blank values only
        // 0 - the field does not have a mix of text and other values
        if (!(isContainsString || (aDPTypes.size() > 1) || (isContainsBlank && aDPTypesWithoutBlank.empty())))
            pAttList->add(XML_containsSemiMixedTypes, ToPsz10(false));

        if (!isContainsNonDate)
            pAttList->add(XML_containsNonDate, ToPsz10(false));

        if (isContainsDate)
            pAttList->add(XML_containsDate, ToPsz10(true));

        // default for containsString field is true, so we are writing only when is false
        if (!isContainsString)
            pAttList->add(XML_containsString, ToPsz10(false));

        if (isContainsBlank)
            pAttList->add(XML_containsBlank, ToPsz10(true));

        // XML_containsMixedType possible values:
        // 1 - field contains more than one data type
        // 0 - (Default) only one data type. The field can still contain blank values (that's why we are using aDPTypesWithoutBlank)
        if (aDPTypesWithoutBlank.size() > 1)
            pAttList->add(XML_containsMixedTypes, ToPsz10(true));

        // If field contain mixed types (Date and Numbers), MS Excel is saving only "minDate" and "maxDate" and not "minValue" and "maxValue"
        // Example how Excel is saving mixed Date and Numbers:
        // <sharedItems containsSemiMixedTypes="0" containsDate="1" containsString="0" containsMixedTypes="1" minDate="1900-01-03T22:26:04" maxDate="1900-01-07T14:02:04" />
        // Example how Excel is saving Dates only:
        // <sharedItems containsSemiMixedTypes="0" containsNonDate="0" containsDate="1" containsString="0" minDate="1903-08-24T07:40:48" maxDate="2024-05-23T07:12:00"/>
        if (isContainsNumber)
            pAttList->add(XML_containsNumber, ToPsz10(true));

        if (isValueInteger && isContainsNumber)
            pAttList->add(XML_containsInteger, ToPsz10(true));


        // Number type fields could be mixed with blank types, and it shouldn't be treated as listed items.
        // Example:
        //    <cacheField name="employeeID" numFmtId="0">
        //        <sharedItems containsString="0" containsBlank="1" containsNumber="1" containsInteger="1" minValue="35" maxValue="89"/>
        //    </cacheField>
        if (isContainsNumber)
        {
            pAttList->add(XML_minValue, OString::number(fMin));
            pAttList->add(XML_maxValue, OString::number(fMax));
        }

        if (isContainsDate)
        {
            pAttList->add(XML_minDate, GetExcelFormattedDate(fMin, GetFormatter()).toUtf8());
            pAttList->add(XML_maxDate, GetExcelFormattedDate(fMax, GetFormatter()).toUtf8());
        }

        //if (bListItems) // see TODO above
        {
            pAttList->add(XML_count, OString::number(static_cast<long>(rFieldItems.size())));
        }

        if (isLongText)
        {
            pAttList->add(XML_longText, ToPsz10(true));
        }

        sax_fastparser::XFastAttributeListRef xAttributeList(pAttList);

        pDefStrm->startElement(XML_sharedItems, xAttributeList);

        //if (bListItems) // see TODO above
        {
            for (const ScDPItemData& rItem : rFieldItems)
            {
                switch (rItem.GetType())
                {
                    case ScDPItemData::String:
                        pDefStrm->singleElement(XML_s, XML_v, rItem.GetString().toUtf8());
                    break;
                    case ScDPItemData::Value:
                        if (isContainsDate)
                        {
                            pDefStrm->singleElement(XML_d,
                                XML_v, GetExcelFormattedDate(rItem.GetValue(), GetFormatter()).toUtf8());
                        }
                        else
                            pDefStrm->singleElement(XML_n,
                                XML_v, OString::number(rItem.GetValue()));
                    break;
                    case ScDPItemData::Empty:
                        pDefStrm->singleElement(XML_m);
                    break;
                    case ScDPItemData::Error:
                        pDefStrm->singleElement(XML_e,
                            XML_v, rItem.GetString().toUtf8());
                    break;
                    case ScDPItemData::GroupValue: // Should not happen here!
                    case ScDPItemData::RangeStart:
                        // TODO : What do we do with these types?
                        pDefStrm->singleElement(XML_m);
                    break;
                    default:
                        ;
                }
            }
        }

        pDefStrm->endElement(XML_sharedItems);

        WriteFieldGroup(i, i);

        pDefStrm->endElement(XML_cacheField);
    }

    ScDPObject* pDPObject
        = rCache.GetAllReferences().empty() ? nullptr : *rCache.GetAllReferences().begin();

    for (size_t i = nCount; pDPObject && i < nCount + nGroupFieldCount; ++i)
    {
        const OUString aName = pDPObject->GetDimName(i, o3tl::temporary(bool()));
        // tdf#126748: DPObject might not reference all group fields, when there are several
        // DPObjects referencing this cache. Trying to get a dimension data for a field not used
        // in a given DPObject will give nullptr, and dereferencing it then will crash. To avoid
        // the crash, until there's a correct method to find the names of group fields in cache,
        // just skip the fields, creating bad cache data, which is of course a temporary hack.
        // TODO: reimplement the whole block to get the names from another source, not from first
        // cache reference.
        if (aName.isEmpty())
            break;

        ScDPSaveData* pSaveData = pDPObject->GetSaveData();
        assert(pSaveData);

        const ScDPSaveGroupDimension* pDim = pSaveData->GetDimensionData()->GetNamedGroupDim(aName);
        assert(pDim);

        const SCCOL nBase = rCache.GetDimensionIndex(pDim->GetSourceDimName());
        assert(nBase >= 0);

        pDefStrm->startElement(XML_cacheField, XML_name, aName.toUtf8(), XML_numFmtId,
                               OString::number(0), XML_databaseField, ToPsz10(false));
        WriteFieldGroup(i, nBase);
        pDefStrm->endElement(XML_cacheField);
    }

    pDefStrm->endElement(XML_cacheFields);

    pDefStrm->endElement(XML_pivotCacheDefinition);
}

XclExpXmlPivotTableManager::XclExpXmlPivotTableManager( const XclExpRoot& rRoot ) :
    XclExpRoot(rRoot), maCaches(rRoot) {}

void XclExpXmlPivotTableManager::Initialize()
{
    ScDocument& rDoc = GetDoc();
    if (!rDoc.HasPivotTable())
        // No pivot table to export.
        return;

    ScDPCollection* pDPColl = rDoc.GetDPCollection();
    if (!pDPColl)
        return;

    // Update caches from DPObject
    for (size_t i = 0; i < pDPColl->GetCount(); ++i)
    {
        ScDPObject& rDPObj = (*pDPColl)[i];
        rDPObj.SyncAllDimensionMembers();
        (void)rDPObj.GetOutputRangeByType(sheet::DataPilotOutputRangeType::TABLE);
    }

    // Go through the caches first.

    std::vector<XclExpXmlPivotCaches::Entry> aCaches;
    const ScDPCollection::SheetCaches& rSheetCaches = pDPColl->GetSheetCaches();
    const std::vector<ScRange>& rRanges = rSheetCaches.getAllRanges();
    for (const auto & rRange : rRanges)
    {
        const ScDPCache* pCache = rSheetCaches.getExistingCache(rRange);
        if (!pCache)
            continue;

        // Get all pivot objects that reference this cache, and set up an
        // object to cache ID mapping.
        const ScDPCache::ScDPObjectSet& rRefs = pCache->GetAllReferences();
        for (const auto& rRef : rRefs)
            maCacheIdMap.emplace(rRef, aCaches.size()+1);

        XclExpXmlPivotCaches::Entry aEntry;
        aEntry.mpCache = pCache;
        aEntry.maSrcRange = rRange;
        aCaches.push_back(aEntry); // Cache ID equals position + 1.
    }

    // TODO : Handle name and database caches as well.

    for (size_t i = 0, n = pDPColl->GetCount(); i < n; ++i)
    {
        const ScDPObject& rDPObj = (*pDPColl)[i];

        // Get the cache ID for this pivot table.
        CacheIdMapType::iterator itCache = maCacheIdMap.find(&rDPObj);
        if (itCache == maCacheIdMap.end())
            // No cache ID found.  Something is wrong here...
            continue;

        sal_Int32 nCacheId = itCache->second;
        SCTAB nTab = rDPObj.GetOutRange().aStart.Tab();

        TablesType::iterator it = m_Tables.find(nTab);
        if (it == m_Tables.end())
        {
            // Insert a new instance for this sheet index.
            std::pair<TablesType::iterator, bool> r =
                m_Tables.insert(std::make_pair(nTab, std::make_unique<XclExpXmlPivotTables>(GetRoot(), maCaches)));
            it = r.first;
        }

        XclExpXmlPivotTables *const p = it->second.get();
        p->AppendTable(&rDPObj, nCacheId, i+1);
    }

    maCaches.SetCaches(aCaches);
}

XclExpXmlPivotCaches& XclExpXmlPivotTableManager::GetCaches()
{
    return maCaches;
}

XclExpXmlPivotTables* XclExpXmlPivotTableManager::GetTablesBySheet( SCTAB nTab )
{
    TablesType::iterator const it = m_Tables.find(nTab);
    return it == m_Tables.end() ? nullptr : it->second.get();
}

XclExpXmlPivotTables::Entry::Entry( const ScDPObject* pTable, sal_Int32 nCacheId, sal_Int32 nPivotId ) :
    mpTable(pTable), mnCacheId(nCacheId), mnPivotId(nPivotId) {}

XclExpXmlPivotTables::XclExpXmlPivotTables( const XclExpRoot& rRoot, const XclExpXmlPivotCaches& rCaches ) :
    XclExpRoot(rRoot), mrCaches(rCaches) {}

void XclExpXmlPivotTables::SaveXml( XclExpXmlStream& rStrm )
{
    sax_fastparser::FSHelperPtr& pWSStrm = rStrm.GetCurrentStream(); // worksheet stream

    for (const auto& rTable : maTables)
    {
        const ScDPObject& rObj = *rTable.mpTable;
        sal_Int32 nCacheId = rTable.mnCacheId;
        sal_Int32 nPivotId = rTable.mnPivotId;

        sax_fastparser::FSHelperPtr pPivotStrm = rStrm.CreateOutputStream(
            XclXmlUtils::GetStreamName("xl/pivotTables/", "pivotTable", nPivotId),
            XclXmlUtils::GetStreamName(nullptr, "../pivotTables/pivotTable", nPivotId),
            pWSStrm->getOutputStream(),
            CREATE_XL_CONTENT_TYPE("pivotTable"),
            CREATE_OFFICEDOC_RELATION_TYPE("pivotTable"));

        rStrm.PushStream(pPivotStrm);
        SavePivotTableXml(rStrm, rObj, nCacheId);
        rStrm.PopStream();
    }
}

namespace {

struct DataField
{
    long mnPos; // field index in pivot cache.
    const ScDPSaveDimension* mpDim;

    DataField( long nPos, const ScDPSaveDimension* pDim ) : mnPos(nPos), mpDim(pDim) {}
};

/** Returns an OOXML subtotal function name string. See ECMA-376-1:2016 18.18.43 */
OString GetSubtotalFuncName(ScGeneralFunction eFunc)
{
    switch (eFunc)
    {
        case ScGeneralFunction::SUM:       return "sum";
        case ScGeneralFunction::COUNT:     return "count";
        case ScGeneralFunction::AVERAGE:   return "avg";
        case ScGeneralFunction::MAX:       return "max";
        case ScGeneralFunction::MIN:       return "min";
        case ScGeneralFunction::PRODUCT:   return "product";
        case ScGeneralFunction::COUNTNUMS: return "countA";
        case ScGeneralFunction::STDEV:     return "stdDev";
        case ScGeneralFunction::STDEVP:    return "stdDevP";
        case ScGeneralFunction::VAR:       return "var";
        case ScGeneralFunction::VARP:      return "varP";
        default:;
    }
    return "default";
}

sal_Int32 GetSubtotalAttrToken(ScGeneralFunction eFunc)
{
    switch (eFunc)
    {
        case ScGeneralFunction::SUM:       return XML_sumSubtotal;
        case ScGeneralFunction::COUNT:     return XML_countSubtotal;
        case ScGeneralFunction::AVERAGE:   return XML_avgSubtotal;
        case ScGeneralFunction::MAX:       return XML_maxSubtotal;
        case ScGeneralFunction::MIN:       return XML_minSubtotal;
        case ScGeneralFunction::PRODUCT:   return XML_productSubtotal;
        case ScGeneralFunction::COUNTNUMS: return XML_countASubtotal;
        case ScGeneralFunction::STDEV:     return XML_stdDevSubtotal;
        case ScGeneralFunction::STDEVP:    return XML_stdDevPSubtotal;
        case ScGeneralFunction::VAR:       return XML_varSubtotal;
        case ScGeneralFunction::VARP:      return XML_varPSubtotal;
        default:;
    }
    return XML_defaultSubtotal;
}

// An item is expected to contain sequences of css::xml::FastAttribute and css::xml::Attribute
void WriteGrabBagItemToStream(XclExpXmlStream& rStrm, sal_Int32 tokenId, const css::uno::Any& rItem)
{
    if (css::uno::Sequence<css::uno::Any> aSeqs; rItem >>= aSeqs)
    {
        auto& pStrm = rStrm.GetCurrentStream();
        pStrm->write("<")->writeId(tokenId);

        css::uno::Sequence<css::xml::FastAttribute> aFastSeq;
        css::uno::Sequence<css::xml::Attribute> aUnkSeq;
        for (const auto& a : std::as_const(aSeqs))
        {
            if (a >>= aFastSeq)
            {
                for (const auto& rAttr : std::as_const(aFastSeq))
                    rStrm.WriteAttributes(rAttr.Token, rAttr.Value);
            }
            else if (a >>= aUnkSeq)
            {
                for (const auto& rAttr : std::as_const(aUnkSeq))
                    pStrm->write(" ")
                        ->write(rAttr.Name)
                        ->write("=\"")
                        ->writeEscaped(rAttr.Value)
                        ->write("\"");
            }
        }

        pStrm->write("/>");
    }
}
}

void XclExpXmlPivotTables::SavePivotTableXml( XclExpXmlStream& rStrm, const ScDPObject& rDPObj, sal_Int32 nCacheId )
{
    typedef std::unordered_map<OUString, long> NameToIdMapType;

    const XclExpXmlPivotCaches::Entry* pCacheEntry = mrCaches.GetCache(nCacheId);
    if (!pCacheEntry)
        // Something is horribly wrong.  Check your logic.
        return;

    const ScDPCache& rCache = *pCacheEntry->mpCache;

    const ScDPSaveData& rSaveData = *rDPObj.GetSaveData();

    size_t nFieldCount = rCache.GetFieldCount() + rCache.GetGroupFieldCount();
    std::vector<const ScDPSaveDimension*> aCachedDims;
    NameToIdMapType aNameToIdMap;

    aCachedDims.reserve(nFieldCount);
    for (size_t i = 0; i < nFieldCount; ++i)
    {
        OUString aName = const_cast<ScDPObject&>(rDPObj).GetDimName(i, o3tl::temporary(bool()));
        aNameToIdMap.emplace(aName, aCachedDims.size());
        const ScDPSaveDimension* pDim = rSaveData.GetExistingDimensionByName(aName);
        aCachedDims.push_back(pDim);
    }

    std::vector<long> aRowFields;
    std::vector<long> aColFields;
    std::vector<long> aPageFields;
    std::vector<DataField> aDataFields;

    long nDataDimCount = rSaveData.GetDataDimensionCount();
    // Use dimensions in the save data to get their correct ordering.
    // Dimension order here is significant as they specify the order of
    // appearance in each axis.
    const ScDPSaveData::DimsType& rDims = rSaveData.GetDimensions();
    bool bTabularMode = false;
    for (const auto & i : rDims)
    {
        const ScDPSaveDimension& rDim = *i;

        long nPos = -1; // position in cache
        if (rDim.IsDataLayout())
            nPos = -2; // Excel uses an index of -2 to indicate a data layout field.
        else
        {
            OUString aSrcName = ScDPUtil::getSourceDimensionName(rDim.GetName());
            NameToIdMapType::iterator it = aNameToIdMap.find(aSrcName);
            if (it != aNameToIdMap.end())
                nPos = it->second;

            if (nPos == -1)
                continue;

            if (!aCachedDims[nPos])
                continue;
        }

        sheet::DataPilotFieldOrientation eOrient = rDim.GetOrientation();

        switch (eOrient)
        {
            case sheet::DataPilotFieldOrientation_COLUMN:
                if (nPos == -2 && nDataDimCount <= 1)
                    break;
                aColFields.push_back(nPos);
            break;
            case sheet::DataPilotFieldOrientation_ROW:
                aRowFields.push_back(nPos);
            break;
            case sheet::DataPilotFieldOrientation_PAGE:
                aPageFields.push_back(nPos);
            break;
            case sheet::DataPilotFieldOrientation_DATA:
                aDataFields.emplace_back(nPos, &rDim);
            break;
            case sheet::DataPilotFieldOrientation_HIDDEN:
            default:
                ;
        }
        if(rDim.GetLayoutInfo())
            bTabularMode |= (rDim.GetLayoutInfo()->LayoutMode == sheet::DataPilotFieldLayoutMode::TABULAR_LAYOUT);
    }

    sax_fastparser::FSHelperPtr& pPivotStrm = rStrm.GetCurrentStream();
    pPivotStrm->startElement(XML_pivotTableDefinition,
        XML_xmlns, rStrm.getNamespaceURL(OOX_NS(xls)).toUtf8(),
        XML_name, rDPObj.GetName().toUtf8(),
        XML_cacheId, OString::number(nCacheId),
        XML_applyNumberFormats, ToPsz10(false),
        XML_applyBorderFormats, ToPsz10(false),
        XML_applyFontFormats, ToPsz10(false),
        XML_applyPatternFormats, ToPsz10(false),
        XML_applyAlignmentFormats, ToPsz10(false),
        XML_applyWidthHeightFormats, ToPsz10(false),
        XML_dataCaption, "Values",
        XML_useAutoFormatting, ToPsz10(false),
        XML_itemPrintTitles, ToPsz10(true),
        XML_indent, ToPsz10(false),
        XML_outline, ToPsz10(!bTabularMode),
        XML_outlineData, ToPsz10(!bTabularMode),
        XML_compact, ToPsz10(false),
        XML_compactData, ToPsz10(false));

    // NB: Excel's range does not include page field area (if any).
    ScRange aOutRange = rDPObj.GetOutputRangeByType(sheet::DataPilotOutputRangeType::TABLE);

    sal_Int32 nFirstHeaderRow = rDPObj.GetHeaderLayout() ? 2 : 1;
    sal_Int32 nFirstDataRow = 2;
    sal_Int32 nFirstDataCol = 1;
    ScRange aResRange = rDPObj.GetOutputRangeByType(sheet::DataPilotOutputRangeType::RESULT);

    if (!aOutRange.IsValid())
        aOutRange = rDPObj.GetOutRange();

    if (aOutRange.IsValid() && aResRange.IsValid())
    {
        nFirstDataRow = aResRange.aStart.Row() - aOutRange.aStart.Row();
        nFirstDataCol = aResRange.aStart.Col() - aOutRange.aStart.Col();
    }

    pPivotStrm->write("<")->writeId(XML_location);
    rStrm.WriteAttributes(XML_ref,
        XclXmlUtils::ToOString(rStrm.GetRoot().GetDoc(), aOutRange),
        XML_firstHeaderRow, OUString::number(nFirstHeaderRow),
        XML_firstDataRow, OUString::number(nFirstDataRow),
        XML_firstDataCol, OUString::number(nFirstDataCol));

    if (!aPageFields.empty())
    {
        rStrm.WriteAttributes(XML_rowPageCount, OUString::number(static_cast<long>(aPageFields.size())));
        rStrm.WriteAttributes(XML_colPageCount, OUString::number(1));
    }

    pPivotStrm->write("/>");

    // <pivotFields> - It must contain all fields in the pivot cache even if
    // only some of them are used in the pivot table.  The order must be as
    // they appear in the cache.

    pPivotStrm->startElement(XML_pivotFields,
        XML_count, OString::number(static_cast<long>(aCachedDims.size())));

    for (size_t i = 0; i < nFieldCount; ++i)
    {
        const ScDPSaveDimension* pDim = aCachedDims[i];
        if (!pDim)
        {
            pPivotStrm->singleElement(XML_pivotField,
                XML_compact, ToPsz10(false),
                XML_showAll, ToPsz10(false));
            continue;
        }

        bool bDimInTabularMode = false;
        if(pDim->GetLayoutInfo())
            bDimInTabularMode = (pDim->GetLayoutInfo()->LayoutMode == sheet::DataPilotFieldLayoutMode::TABULAR_LAYOUT);

        sheet::DataPilotFieldOrientation eOrient = pDim->GetOrientation();

        if (eOrient == sheet::DataPilotFieldOrientation_HIDDEN)
        {
            if(bDimInTabularMode)
            {
                pPivotStrm->singleElement(XML_pivotField,
                    XML_compact, ToPsz10(false),
                    XML_showAll, ToPsz10(false),
                    XML_outline, ToPsz10(false));
            }
            else
            {
                pPivotStrm->singleElement(XML_pivotField,
                    XML_compact, ToPsz10(false),
                    XML_showAll, ToPsz10(false));
            }
            continue;
        }

        if (eOrient == sheet::DataPilotFieldOrientation_DATA)
        {
            if(bDimInTabularMode)
            {
                pPivotStrm->singleElement(XML_pivotField,
                    XML_dataField, ToPsz10(true),
                    XML_compact, ToPsz10(false),
                    XML_showAll, ToPsz10(false),
                    XML_outline, ToPsz10(false));
            }
            else
            {
                pPivotStrm->singleElement(XML_pivotField,
                    XML_dataField, ToPsz10(true),
                    XML_compact, ToPsz10(false),
                    XML_showAll, ToPsz10(false));
            }
            continue;
        }

        // Dump field items.
        std::vector<ScDPLabelData::Member> aMembers;
        {
            // We need to get the members in actual order, getting which requires non-const reference here
            auto& dpo = const_cast<ScDPObject&>(rDPObj);
            dpo.GetMembers(i, dpo.GetUsedHierarchy(i), aMembers);
        }

        std::vector<OUString> aCacheFieldItems;
        if (i < rCache.GetFieldCount() && !rCache.GetGroupType(i))
        {
            for (const auto& it : rCache.GetDimMemberValues(i))
            {
                OUString sFormattedName;
                if (it.HasStringData() || it.IsEmpty())
                    sFormattedName = it.GetString();
                else
                    sFormattedName = const_cast<ScDPObject&>(rDPObj).GetFormattedString(
                        pDim->GetName(), it.GetValue());
                aCacheFieldItems.push_back(sFormattedName);
            }
        }
        else
        {
            aCacheFieldItems = SortGroupItems(rCache, i);
        }
        // The pair contains the member index in cache and if it is hidden
        std::vector< std::pair<size_t, bool> > aMemberSequence;
        std::set<size_t> aUsedCachePositions;
        for (const auto & rMember : aMembers)
        {
            auto it = std::find(aCacheFieldItems.begin(), aCacheFieldItems.end(), rMember.maName);
            if (it != aCacheFieldItems.end())
            {
                size_t nCachePos = static_cast<size_t>(std::distance(aCacheFieldItems.begin(), it));
                auto aInserted = aUsedCachePositions.insert(nCachePos);
                if (aInserted.second)
                    aMemberSequence.emplace_back(std::make_pair(nCachePos, !rMember.mbVisible));
            }
        }
        // Now add all remaining cache items as hidden
        for (size_t nItem = 0; nItem < aCacheFieldItems.size(); ++nItem)
        {
            if (aUsedCachePositions.find(nItem) == aUsedCachePositions.end())
                aMemberSequence.emplace_back(nItem, true);
        }

        // tdf#125086: check if this field *also* appears in Data region
        bool bAppearsInData = false;
        {
            OUString aSrcName = ScDPUtil::getSourceDimensionName(pDim->GetName());
            const auto it = std::find_if(
                aDataFields.begin(), aDataFields.end(), [&aSrcName](const DataField& rDataField) {
                    OUString aThisName
                        = ScDPUtil::getSourceDimensionName(rDataField.mpDim->GetName());
                    return aThisName == aSrcName;
                });
            if (it != aDataFields.end())
                bAppearsInData = true;
        }

        auto pAttList = sax_fastparser::FastSerializerHelper::createAttrList();
        pAttList->add(XML_axis, toOOXMLAxisType(eOrient));
        if (bAppearsInData)
            pAttList->add(XML_dataField, ToPsz10(true));
        pAttList->add(XML_compact, ToPsz10(false));
        pAttList->add(XML_showAll, ToPsz10(false));

        long nSubTotalCount = pDim->GetSubTotalsCount();
        std::vector<OString> aSubtotalSequence;
        bool bHasDefaultSubtotal = false;
        for (long nSubTotal = 0; nSubTotal < nSubTotalCount; ++nSubTotal)
        {
            ScGeneralFunction eFunc = pDim->GetSubTotalFunc(nSubTotal);
            aSubtotalSequence.push_back(GetSubtotalFuncName(eFunc));
            sal_Int32 nAttToken = GetSubtotalAttrToken(eFunc);
            if (nAttToken == XML_defaultSubtotal)
                bHasDefaultSubtotal = true;
            else if (!pAttList->hasAttribute(nAttToken))
                pAttList->add(nAttToken, ToPsz10(true));
        }
        // XML_defaultSubtotal is true by default; only write it if it's false
        if (!bHasDefaultSubtotal)
            pAttList->add(XML_defaultSubtotal, ToPsz10(false));

        if(bDimInTabularMode)
            pAttList->add( XML_outline, ToPsz10(false));
        sax_fastparser::XFastAttributeListRef xAttributeList(pAttList);
        pPivotStrm->startElement(XML_pivotField, xAttributeList);

        pPivotStrm->startElement(XML_items,
            XML_count, OString::number(static_cast<long>(aMemberSequence.size() + aSubtotalSequence.size())));

        for (const auto & nMember : aMemberSequence)
        {
            auto pItemAttList = sax_fastparser::FastSerializerHelper::createAttrList();
            if (nMember.second)
                pItemAttList->add(XML_h, ToPsz10(true));
            pItemAttList->add(XML_x, OString::number(static_cast<long>(nMember.first)));
            sax_fastparser::XFastAttributeListRef xItemAttributeList(pItemAttList);
            pPivotStrm->singleElement(XML_item, xItemAttributeList);
        }

        for (const OString& sSubtotal : aSubtotalSequence)
        {
            pPivotStrm->singleElement(XML_item, XML_t, sSubtotal);
        }

        pPivotStrm->endElement(XML_items);
        pPivotStrm->endElement(XML_pivotField);
    }

    pPivotStrm->endElement(XML_pivotFields);

    // <rowFields>

    if (!aRowFields.empty())
    {
        pPivotStrm->startElement(XML_rowFields,
            XML_count, OString::number(static_cast<long>(aRowFields.size())));

        for (const auto& rRowField : aRowFields)
        {
            pPivotStrm->singleElement(XML_field, XML_x, OString::number(rRowField));
        }

        pPivotStrm->endElement(XML_rowFields);
    }

    // <rowItems>

    // <colFields>

    if (!aColFields.empty())
    {
        pPivotStrm->startElement(XML_colFields,
            XML_count, OString::number(static_cast<long>(aColFields.size())));

        for (const auto& rColField : aColFields)
        {
            pPivotStrm->singleElement(XML_field, XML_x, OString::number(rColField));
        }

        pPivotStrm->endElement(XML_colFields);
    }

    // <colItems>

    // <pageFields>

    if (!aPageFields.empty())
    {
        pPivotStrm->startElement(XML_pageFields,
            XML_count, OString::number(static_cast<long>(aPageFields.size())));

        for (const auto& rPageField : aPageFields)
        {
            pPivotStrm->singleElement(XML_pageField,
                XML_fld, OString::number(rPageField),
                XML_hier, OString::number(-1)); // TODO : handle this correctly.
        }

        pPivotStrm->endElement(XML_pageFields);
    }

    // <dataFields>

    if (!aDataFields.empty())
    {
        css::uno::Reference<css::container::XNameAccess> xDimsByName;
        if (auto xDimSupplier = const_cast<ScDPObject&>(rDPObj).GetSource())
            xDimsByName = xDimSupplier->getDimensions();

        pPivotStrm->startElement(XML_dataFields,
            XML_count, OString::number(static_cast<long>(aDataFields.size())));

        for (const auto& rDataField : aDataFields)
        {
            long nDimIdx = rDataField.mnPos;
            assert(aCachedDims[nDimIdx]); // the loop above should have screened for NULL's.
            const ScDPSaveDimension& rDim = *rDataField.mpDim;
            std::optional<OUString> pName = rDim.GetLayoutName();
            // tdf#124651: despite being optional in CT_DataField according to ECMA-376 Part 1,
            // Excel (at least 2016) seems to insist on the presence of "name" attribute in
            // dataField element.
            // tdf#124881: try to create a meaningful name; don't use empty string.
            if (!pName)
                pName = ScDPUtil::getDisplayedMeasureName(
                    rDim.GetName(), ScDPUtil::toSubTotalFunc(rDim.GetFunction()));
            auto pItemAttList = sax_fastparser::FastSerializerHelper::createAttrList();
            pItemAttList->add(XML_name, pName->toUtf8());
            pItemAttList->add(XML_fld, OString::number(nDimIdx));
            const char* pSubtotal = toOOXMLSubtotalType(rDim.GetFunction());
            if (pSubtotal)
                pItemAttList->add(XML_subtotal, pSubtotal);
            if (xDimsByName)
            {
                try
                {
                    css::uno::Reference<css::beans::XPropertySet> xDimProps(
                        xDimsByName->getByName(rDim.GetName()), uno::UNO_QUERY_THROW);
                    css::uno::Any aVal = xDimProps->getPropertyValue(SC_UNONAME_NUMFMT);
                    sal_uInt32 nScNumFmt = aVal.get<sal_uInt32>();
                    sal_uInt16 nXclNumFmt = GetRoot().GetNumFmtBuffer().Insert(nScNumFmt);
                    pItemAttList->add(XML_numFmtId, OString::number(nXclNumFmt));
                }
                catch (uno::Exception&)
                {
                    SAL_WARN("sc.filter",
                             "Couldn't get number format for data field " << rDim.GetName());
                    // Just skip exporting number format
                }
            }
            sax_fastparser::XFastAttributeListRef xItemAttributeList(pItemAttList);
            pPivotStrm->singleElement(XML_dataField, xItemAttributeList);
        }

        pPivotStrm->endElement(XML_dataFields);
    }

    // Now add style info (use grab bag, or just a set which is default on Excel 2007 through 2016)
    if (const auto [bHas, aVal] = rDPObj.GetInteropGrabBagValue("pivotTableStyleInfo"); bHas)
        WriteGrabBagItemToStream(rStrm, XML_pivotTableStyleInfo, aVal);
    else
        pPivotStrm->singleElement(XML_pivotTableStyleInfo, XML_name, "PivotStyleLight16",
                                  XML_showRowHeaders, "1", XML_showColHeaders, "1",
                                  XML_showRowStripes, "0", XML_showColStripes, "0",
                                  XML_showLastColumn, "1");

    OUString aBuf = "../pivotCache/pivotCacheDefinition" +
        OUString::number(nCacheId) +
        ".xml";

    rStrm.addRelation(
        pPivotStrm->getOutputStream(),
        CREATE_OFFICEDOC_RELATION_TYPE("pivotCacheDefinition"),
        aBuf);

    pPivotStrm->endElement(XML_pivotTableDefinition);
}

void XclExpXmlPivotTables::AppendTable( const ScDPObject* pTable, sal_Int32 nCacheId, sal_Int32 nPivotId )
{
    maTables.emplace_back(pTable, nCacheId, nPivotId);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */