OpenXLSX 1.12.1
Modern C++ Excel Library (Fork of OpenXLSX by Kenneth Troldal Balslev)
Loading...
Searching...
No Matches
XLStreamWriter.hpp
Go to the documentation of this file.
1/*
2 * OpenXLSX-NX - Modern High-Performance C++ Excel Library
3 *
4 * Original work Copyright (c) 2018-2025, Kenneth Troldal Balslev and OpenXLSX contributors
5 * Modified work Copyright (c) 2026, Curry Tang and OpenXLSX-NX contributors
6 *
7 * Distributed under the BSD 3-Clause License.
8 * See LICENSE.md in the project root or https://opensource.org/licenses/BSD-3-Clause
9 */
10
11//
12// XLStreamWriter — streaming worksheet write API (excelize-compatible phases).
13// Phase 0: cols / panes / page breaks (before first row)
14// Phase 1: sheetData rows (strictly increasing row numbers)
15// Phase 2: mergeCells / tableParts (injected at close)
16//
17
18#ifndef OPENXLSX_XLSTREAMWRITER_HPP
19#define OPENXLSX_XLSTREAMWRITER_HPP
20
21#include "OpenXLSX-Exports.hpp"
22#include "XLCellValue.hpp"
23#include "XLDateTime.hpp"
24#include "XLSharedStrings.hpp"
25#include "XLStyles_Common.hpp" // XLStyleIndex
26#include <cstddef>
27#include <cstdint>
28#include <filesystem>
29#include <fstream>
30#include <initializer_list>
31#include <optional>
32#include <string>
33#include <string_view>
34#include <vector>
35
36namespace OpenXLSX
37{
38
39 class XLWorksheet;
40
46 enum class XLStreamOpenMode : uint8_t { Auto = 0, Fresh = 1, Hybrid = 2 };
47
53 enum class XLStreamDimensionMode : uint8_t {
54 FixedSlot = 0, // default: accurate used-range via fixed-width in-place patch
55 OmitPatch = 1 // keep A1:XFD1048576 placeholder (no seek patch)
56 };
57
61 struct OPENXLSX_EXPORT XLStreamWriteOptions
62 {
68 size_t memorySpillThreshold{4 * 1024 * 1024};
70 std::filesystem::path tempDir{};
71 bool useSharedStrings{false};
72 size_t maxUniqueStrings{100000};
78 size_t maxSstBytes{64 * 1024 * 1024};
89 size_t hybridHeaderSpillThreshold{4 * 1024 * 1024};
94 std::string defaultDateTimeFormat{"yyyy-mm-dd hh:mm:ss"};
95 };
96
101 struct OPENXLSX_EXPORT XLStreamPanesOptions
102 {
104 uint16_t freezeCols{0};
106 uint32_t freezeRows{0};
111 std::string topLeftCell{};
113 bool split{false};
114 double xSplit{0.0};
115 double ySplit{0.0};
117 std::string activePane{"bottomRight"};
118 };
119
123 struct OPENXLSX_EXPORT XLStreamRowOpts
124 {
125 std::optional<double> height; // points; writes ht + customHeight="1"
126 std::optional<bool> hidden;
127 std::optional<uint8_t> outlineLevel; // 0–7
128 std::optional<XLStyleIndex> styleIndex; // row s= + customFormat="1"
129 };
130
135 struct OPENXLSX_EXPORT XLStreamTableOptions
136 {
137 std::string name{"Table1"};
138 std::string styleName{"TableStyleMedium2"};
139 std::string range; // e.g. "A1:D10"
140 bool showRowStripes{true};
141 bool showColumnStripes{false};
142 bool showFirstColumn{false};
143 bool showLastColumn{false};
145 std::vector<std::string> headers;
146 };
147
151 struct OPENXLSX_EXPORT XLStreamHyperlink
152 {
153 std::string cellRef; // e.g. "A1"
154 std::string target; // URL or internal location (Sheet1!A1)
155 bool external{true};
156 std::string tooltip;
157 std::string display; // optional display attribute for internal links
158 };
159
169
173 class OPENXLSX_EXPORT XLStreamCell
174 {
175 public:
176 explicit XLStreamCell(XLCellValue val) : value(std::move(val)), styleIndex(std::nullopt), formula(std::nullopt) {}
177
178 XLStreamCell(XLCellValue val, XLStyleIndex style) : value(std::move(val)), styleIndex(style), formula(std::nullopt) {}
179
180 XLStreamCell(XLCellValue val, XLStyleIndex style, std::string formulaText)
181 : value(std::move(val)), styleIndex(style), formula(std::move(formulaText))
182 {}
183
184 static XLStreamCell withFormula(std::string formulaText, XLCellValue cached = XLCellValue {})
185 {
186 XLStreamCell cell(std::move(cached));
187 cell.formula = std::move(formulaText);
188 return cell;
189 }
190
194 static XLStreamCell withArrayFormula(std::string formulaText, std::string ref = {}, XLCellValue cached = XLCellValue {})
195 {
196 XLStreamCell cell = withFormula(std::move(formulaText), std::move(cached));
197 cell.formulaType = XLStreamFormulaType::Array;
198 if (!ref.empty()) cell.formulaRef = std::move(ref);
199 return cell;
200 }
201
205 static XLStreamCell withSharedFormula(int si, std::string formulaText = {}, std::string ref = {}, XLCellValue cached = XLCellValue {})
206 {
207 XLStreamCell cell = withFormula(std::move(formulaText), std::move(cached));
208 cell.formulaType = XLStreamFormulaType::Shared;
209 cell.formulaSi = si;
210 if (!ref.empty()) cell.formulaRef = std::move(ref);
211 return cell;
212 }
213
219 static XLStreamCell withDateTime(const XLDateTime& dt, std::optional<XLStyleIndex> style = std::nullopt)
220 {
221 XLStreamCell cell(XLCellValue(dt.serial()));
222 cell.styleIndex = style;
223 cell.treatAsDate = true;
224 return cell;
225 }
226
228 std::optional<XLStyleIndex> styleIndex;
229 std::optional<std::string> formula;
231 bool treatAsDate{false};
232
234 std::optional<std::string> formulaRef; // array/shared ref attribute
235 std::optional<int> formulaSi; // shared formula index
236 bool formulaCa{false}; // calculate always
237 };
238
239 class OPENXLSX_EXPORT XLStreamWriter
240 {
241 public:
242 XLStreamWriter() = default;
245
246 XLStreamWriter(XLStreamWriter&& other) noexcept;
247 XLStreamWriter& operator=(XLStreamWriter&& other) noexcept;
248
250
251 bool isStreamActive() const;
252
253 // ── Phase 0 (must be called before any row) ──────────────────────────
254
258 void setColWidth(uint16_t minCol, uint16_t maxCol, double width);
259
263 void setColVisible(uint16_t minCol, uint16_t maxCol, bool visible);
264
268 void setColOutlineLevel(uint16_t col, uint8_t level);
269
273 void setColStyle(uint16_t minCol, uint16_t maxCol, XLStyleIndex style);
274
280 void setPanesXml(std::string panesXml);
281
285 void setPanes(const XLStreamPanesOptions& panes);
286
290 void freezePanes(const std::string& topLeftCell);
291
295 void freezePanes(uint16_t cols, uint32_t rows);
296
300 void insertPageBreak(std::string_view cellRef);
301
302 // ── Phase 1: rows ────────────────────────────────────────────────────
303
304 void appendRow(const std::vector<XLCellValue>& values);
305 void appendRow(const std::vector<XLCellValue>& values, const XLStreamRowOpts& opts);
306 void appendRow(std::initializer_list<XLCellValue> values);
307 void appendRow(std::initializer_list<XLCellValue> values, const XLStreamRowOpts& opts);
308
309 void appendRow(const std::vector<XLStreamCell>& cells);
310 void appendRow(const std::vector<XLStreamCell>& cells, const XLStreamRowOpts& opts);
311 void appendRow(std::initializer_list<XLStreamCell> cells);
312 void appendRow(std::initializer_list<XLStreamCell> cells, const XLStreamRowOpts& opts);
313
314 void setRow(uint32_t row, uint16_t startCol, const std::vector<XLStreamCell>& cells, const XLStreamRowOpts& opts = {});
315 void setRow(uint32_t row, uint16_t startCol, const std::vector<XLCellValue>& values, const XLStreamRowOpts& opts = {});
316 void setRow(uint32_t row, uint16_t startCol, std::initializer_list<XLStreamCell> cells, const XLStreamRowOpts& opts = {});
317 void setRow(uint32_t row, uint16_t startCol, std::initializer_list<XLCellValue> values, const XLStreamRowOpts& opts = {});
318
319 void setRow(const std::string& cellRef, const std::vector<XLStreamCell>& cells, const XLStreamRowOpts& opts = {});
320 void setRow(const std::string& cellRef, const std::vector<XLCellValue>& values, const XLStreamRowOpts& opts = {});
321 void setRow(const std::string& cellRef, std::initializer_list<XLStreamCell> cells, const XLStreamRowOpts& opts = {});
322 void setRow(const std::string& cellRef, std::initializer_list<XLCellValue> values, const XLStreamRowOpts& opts = {});
323
324 // ── Phase 2 (after rows, before close) ───────────────────────────────
325
329 void mergeCell(std::string_view topLeft, std::string_view bottomRight);
330
335 void addTable(const XLStreamTableOptions& table);
336
340 void setAutoFilter(std::string_view range);
341
345 void addHyperlink(std::string_view cellRef, std::string_view url, std::string_view tooltip = {});
346
350 void addInternalHyperlink(std::string_view cellRef, std::string_view location, std::string_view tooltip = {});
351
355 void close();
356
357 void flush() { close(); }
358
359 std::string getTempFilePath() const;
360
361 uint32_t lastRow() const { return m_lastWrittenRow; }
362 uint16_t maxColumn() const { return m_maxColumn; }
363
365 uint64_t bytesWritten() const { return m_sinkBytesWritten; }
366
368 bool hasDimensionSlot() const { return m_dimensionSlotSize > 0; }
369
370 const XLStreamWriteOptions& options() const { return m_options; }
371
372 private:
373 friend class XLWorksheet;
374
376
377 // Legacy constructor path
378 explicit XLStreamWriter(XLWorksheet* worksheet, bool useSharedStrings, size_t maxUniqueStrings);
379
380 template<typename T>
381 void setRowImpl(uint32_t row, uint16_t startCol, const std::vector<T>& items, const XLStreamRowOpts* opts);
382
383 void writeRowOpen(uint32_t row, const XLStreamRowOpts* opts);
384 void writeCellValueBody(const XLCellValue& value);
385 void flushWriteBuffer();
386 void flushSheetDataClose();
387 void patchDimension();
388 void installDimensionSlot();
389 void markWriterOpen(bool open) noexcept;
390 void checkStreamWritable() const;
391 void checkPhase0() const;
392 void ensureSheetDataStarted();
393 void sinkWrite(std::string_view data);
394 void sinkSpillToFile();
395 void materializeToWorksheet();
396 std::string buildColsXml() const;
397 std::string buildMergeCellsXml() const;
398 std::string buildPageBreaksXml() const;
399 std::string buildAutoFilterXml() const;
400 void writeFormulaOpenTag(const XLStreamCell* cellMeta, const std::string& formulaText);
401 void normalizeColRange(uint16_t& minCol, uint16_t& maxCol) const;
402 void injectBeforeSheetData(std::string fragment);
403 void streamPreHeaderToSink();
404 std::string buildPanesXml(const XLStreamPanesOptions& panes) const;
405 XLStyleIndex ensureDefaultDateStyle();
406
407 struct ColDirective
408 {
409 uint16_t minCol{1};
410 uint16_t maxCol{1};
411 std::optional<double> width;
412 std::optional<bool> hidden;
413 std::optional<uint8_t> outlineLevel;
414 std::optional<XLStyleIndex> styleIndex;
415 };
416
417 static constexpr size_t kRowFlushThreshold = 256 * 1024;
418 static constexpr double kMaxRowHeight = 409.0;
419 static constexpr double kMaxColWidth = 255.0;
421 static constexpr std::string_view kDimensionSlot = R"(<dimension ref="A1:XFD1048576"/>)";
422
423 XLStreamWriteOptions m_options{};
424
425 // Sink: memory-first, optional spill
426 std::string m_memBuffer;
427 std::filesystem::path m_tempPath;
428 std::ofstream m_fileStream;
429 bool m_usingFile{false};
430 uint64_t m_sinkBytesWritten{0};
431
432 // Fixed-slot dimension patch (O(1) close; no full-file reload)
433 uint64_t m_dimensionByteOffset{0};
434 size_t m_dimensionSlotSize{0};
435
436 // Header assembly (not flushed until first row / close)
437 std::string m_preContent; // in-memory header (Hybrid may include existing rows)
438 std::filesystem::path m_preHeaderPath; // large Hybrid header kept on disk
439 bool m_preHeaderFileBacked{false};
440 std::string m_bottomHalf; // from </sheetData> inclusive
441 bool m_headerWritten{false};
442 bool m_sheetDataStarted{false}; // Phase 1 entered
443 bool m_preHasOpenSheetData{false}; // preContent already contains <sheetData>
444
445 std::vector<ColDirective> m_colDirectives;
446 std::string m_panesXml;
447 std::vector<std::string> m_mergeRefs; // "A1:B2"
448 std::vector<std::string> m_rowBreaks; // row numbers as strings
449 std::vector<std::string> m_colBreaks;
450 std::optional<XLStreamTableOptions> m_table;
451 std::optional<std::string> m_autoFilterRange;
452 std::vector<XLStreamHyperlink> m_hyperlinks;
453
454 uint32_t m_currentRow{1};
455 uint32_t m_lastWrittenRow{0};
456 uint16_t m_maxColumn{0};
457 uint16_t m_baseMaxCol{0};
458 uint32_t m_baseLastRow{0};
459 bool m_active{false};
460
461 std::string m_writeBuffer;
462
463 XLWorksheet* m_worksheet{nullptr};
464 bool m_wroteFormula{false};
465 size_t m_sstBytesUsed{0};
466 XLStyleIndex m_cachedDateStyle{XLInvalidStyleIndex};
467 bool m_dateStyleReady{false};
468
469 mutable FlatHashMap<std::string_view, int32_t> m_localCache{};
470 static constexpr size_t kLocalCacheLimit = 5000;
471 };
472
473} // namespace OpenXLSX
474#endif // OPENXLSX_XLSTREAMWRITER_HPP
Class encapsulating a cell value.
Definition XLCellValue.hpp:89
Manages date and time values according to the Excel 1900 date system.
Definition XLDateTime.hpp:40
double serial() const
Definition XLDateTime.cpp:143
A structure that represents a cell to be appended via the streaming API.
Definition XLStreamWriter.hpp:174
static XLStreamCell withArrayFormula(std::string formulaText, std::string ref={}, XLCellValue cached=XLCellValue {})
Array formula (t="array", optional ref= for multi-cell CSE).
Definition XLStreamWriter.hpp:194
static XLStreamCell withSharedFormula(int si, std::string formulaText={}, std::string ref={}, XLCellValue cached=XLCellValue {})
Shared formula master (t="shared" si=… ref=…) or dependent (empty formula body, si= only).
Definition XLStreamWriter.hpp:205
XLStreamCell(XLCellValue val, XLStyleIndex style)
Definition XLStreamWriter.hpp:178
XLCellValue value
Definition XLStreamWriter.hpp:227
XLStreamCell(XLCellValue val, XLStyleIndex style, std::string formulaText)
Definition XLStreamWriter.hpp:180
std::optional< std::string > formula
Definition XLStreamWriter.hpp:229
XLStreamCell(XLCellValue val)
Definition XLStreamWriter.hpp:176
std::optional< std::string > formulaRef
Definition XLStreamWriter.hpp:234
bool formulaCa
Definition XLStreamWriter.hpp:236
std::optional< XLStyleIndex > styleIndex
Definition XLStreamWriter.hpp:228
std::optional< int > formulaSi
Definition XLStreamWriter.hpp:235
bool treatAsDate
Definition XLStreamWriter.hpp:231
XLStreamFormulaType formulaType
Definition XLStreamWriter.hpp:233
static XLStreamCell withDateTime(const XLDateTime &dt, std::optional< XLStyleIndex > style=std::nullopt)
Date/time cell: stores Excel serial and requests an automatic date number format.
Definition XLStreamWriter.hpp:219
static XLStreamCell withFormula(std::string formulaText, XLCellValue cached=XLCellValue {})
Definition XLStreamWriter.hpp:184
void setColWidth(uint16_t minCol, uint16_t maxCol, double width)
Set column width for [minCol, maxCol] (1-based, inclusive). excelize SetColWidth.
Definition XLStreamWriter.cpp:373
friend class XLWorksheet
Definition XLStreamWriter.hpp:373
void appendRow(const std::vector< XLCellValue > &values)
Definition XLStreamWriter.cpp:1160
uint32_t lastRow() const
Definition XLStreamWriter.hpp:361
void setColOutlineLevel(uint16_t col, uint8_t level)
Column outline level 1–7. excelize SetColOutlineLevel.
Definition XLStreamWriter.cpp:397
void flush()
Definition XLStreamWriter.hpp:357
void setColVisible(uint16_t minCol, uint16_t maxCol, bool visible)
Show/hide columns. excelize SetColVisible.
Definition XLStreamWriter.cpp:386
uint64_t bytesWritten() const
Definition XLStreamWriter.hpp:365
void setPanesXml(std::string panesXml)
Freeze/split panes XML fragment (sheetViews). Must be before first row.
Definition XLStreamWriter.cpp:419
XLStreamWriter(const XLStreamWriter &)=delete
bool isStreamActive() const
Definition XLStreamWriter.cpp:292
void freezePanes(const std::string &topLeftCell)
Freeze panes so that topLeftCell is the first unfrozen cell (e.g. "B2").
Definition XLStreamWriter.cpp:514
void setPanes(const XLStreamPanesOptions &panes)
Structured freeze or split panes (must be before first row). excelize SetPanes.
Definition XLStreamWriter.cpp:508
const XLStreamWriteOptions & options() const
Definition XLStreamWriter.hpp:370
void setColStyle(uint16_t minCol, uint16_t maxCol, XLStyleIndex style)
Apply a cell style index to an entire column range. excelize SetColStyle.
Definition XLStreamWriter.cpp:408
void close()
Flushes buffers, writes footer, patches dimension, deactivates stream.
Definition XLStreamWriter.cpp:1238
uint16_t maxColumn() const
Definition XLStreamWriter.hpp:362
XLStreamWriter & operator=(const XLStreamWriter &)=delete
void insertPageBreak(std::string_view cellRef)
Record a horizontal/vertical page break at a cell (stored until close).
Definition XLStreamWriter.cpp:546
void setRow(uint32_t row, uint16_t startCol, const std::vector< XLStreamCell > &cells, const XLStreamRowOpts &opts={})
Definition XLStreamWriter.cpp:1194
bool hasDimensionSlot() const
Definition XLStreamWriter.hpp:368
A class encapsulating an Excel worksheet. Access to XLWorksheet objects should be via the workbook ob...
Definition XLWorksheet.hpp:132
Definition IXLCellProvider.hpp:24
XLStreamOpenMode
How streamWriter materializes the worksheet header.
Definition XLStreamWriter.hpp:46
@ Auto
Definition XLStreamWriter.hpp:46
@ Hybrid
Definition XLStreamWriter.hpp:46
@ Fresh
Definition XLStreamWriter.hpp:46
@ Normal
Definition XLPivotTable.hpp:30
XLStreamFormulaType
Formula type attributes for shared / array formulas (OOXML <f t=…>).
Definition XLStreamWriter.hpp:163
@ Array
Definition XLStreamWriter.hpp:165
@ Normal
Definition XLStreamWriter.hpp:164
@ Shared
Definition XLStreamWriter.hpp:166
@ DataTable
Definition XLStreamWriter.hpp:167
size_t XLStyleIndex
Definition XLStyles_Common.hpp:36
XLStreamDimensionMode
How <dimension> is finalized on close without reloading the full sheet XML.
Definition XLStreamWriter.hpp:53
@ OmitPatch
Definition XLStreamWriter.hpp:55
@ FixedSlot
Definition XLStreamWriter.hpp:54
constexpr const XLStyleIndex XLInvalidStyleIndex
Definition XLStyles_Common.hpp:57
Definition XLCellIterator.hpp:131
Structured freeze/split panes for stream writers (excelize SetPanes equivalent).
Definition XLStreamWriter.hpp:102
double ySplit
Definition XLStreamWriter.hpp:115
bool split
Definition XLStreamWriter.hpp:113
uint32_t freezeRows
Definition XLStreamWriter.hpp:106
uint16_t freezeCols
Definition XLStreamWriter.hpp:104
std::string topLeftCell
Optional top-left cell of the scrollable region (1-based address, e.g. "B2").
Definition XLStreamWriter.hpp:111
double xSplit
Definition XLStreamWriter.hpp:114
std::string activePane
Definition XLStreamWriter.hpp:117
Optional row-level attributes for streaming writes (excelize RowOpts equivalent).
Definition XLStreamWriter.hpp:124
std::optional< bool > hidden
Definition XLStreamWriter.hpp:126
std::optional< double > height
Definition XLStreamWriter.hpp:125
std::optional< XLStyleIndex > styleIndex
Definition XLStreamWriter.hpp:128
std::optional< uint8_t > outlineLevel
Definition XLStreamWriter.hpp:127
Minimal table definition for streaming AddTable (excelize-compatible constraints).
Definition XLStreamWriter.hpp:136
bool showColumnStripes
Definition XLStreamWriter.hpp:141
bool showFirstColumn
Definition XLStreamWriter.hpp:142
std::string range
Definition XLStreamWriter.hpp:139
std::string styleName
Definition XLStreamWriter.hpp:138
std::string name
Definition XLStreamWriter.hpp:137
std::vector< std::string > headers
Definition XLStreamWriter.hpp:145
bool showRowStripes
Definition XLStreamWriter.hpp:140
bool showLastColumn
Definition XLStreamWriter.hpp:143
Options for XLStreamWriter construction.
Definition XLStreamWriter.hpp:62
size_t maxUniqueStrings
Definition XLStreamWriter.hpp:72
XLStreamOpenMode openMode
Definition XLStreamWriter.hpp:63
XLStreamDimensionMode dimensionMode
Definition XLStreamWriter.hpp:79
size_t maxSstBytes
Hard budget for unique shared-string payload bytes while streaming.
Definition XLStreamWriter.hpp:78
std::filesystem::path tempDir
Definition XLStreamWriter.hpp:70
size_t hybridHeaderSpillThreshold
Hybrid mode: if the serialized existing sheet XML exceeds this size, keep the pre-sheetData header on...
Definition XLStreamWriter.hpp:89
std::string defaultDateTimeFormat
Default number format for XLStreamCell::withDateTime when no style is given.
Definition XLStreamWriter.hpp:94
bool useSharedStrings
Definition XLStreamWriter.hpp:71
size_t memorySpillThreshold
Spill in-memory buffer to a temp file after this many bytes.
Definition XLStreamWriter.hpp:68
bool strictTableRegistration
When true, addTable registration failures on close throw instead of being swallowed.
Definition XLStreamWriter.hpp:83