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
//! Worksheet representation and cell operations.
use crate::autofilter::AutoFilter;
use crate::cell::{CellValue, InternedString};
use crate::conditional::ConditionalFormatting;
use crate::pagesetup::PageSetup;
use crate::style::CellStyle;
use crate::table::Table;
#[cfg(feature = "fast-hash")]
use hashbrown::HashMap;
#[cfg(not(feature = "fast-hash"))]
use std::collections::HashMap;
use std::sync::Arc;
#[cfg(feature = "fast-hash")]
pub type CellMap = hashbrown::HashMap<u64, CellData, ahash::RandomState>;
#[cfg(not(feature = "fast-hash"))]
pub type CellMap = std::collections::HashMap<u64, CellData>;
#[inline]
pub(crate) fn cell_key(row: u32, column: u32) -> u64 {
((row as u64) << 32) | (column as u64)
}
#[inline]
pub(crate) fn decode_cell_key(key: u64) -> (u32, u32) {
((key >> 32) as u32, key as u32)
}
/// Data associated with a single cell.
#[derive(Clone, Debug, Default)]
pub struct CellData {
/// The cell's value.
pub value: CellValue,
/// Cell style (font, alignment, etc.) - Arc for cheap cloning.
pub style: Option<Arc<CellStyle>>,
/// Style index for writing (preserves original style during roundtrip).
pub style_index: Option<u32>,
/// Number format string. Interned: the same format is shared by every cell
/// in a column, and it is cloned per cell when styles are resolved on save.
pub number_format: Option<InternedString>,
/// Data type (s=string, n=number, b=boolean, d=date). Always one of a fixed
/// set of codes, so it borrows rather than allocating per cell.
pub data_type: Option<&'static str>,
/// Hyperlink URL.
pub hyperlink: Option<String>,
/// Cell comment text.
pub comment: Option<String>,
/// Last calculated result of a formula cell, as the raw `<v>` text.
/// Written back on save so viewers that don't recalculate show a value;
/// `data_type` carries the matching `t` attribute (str/b/e or numeric).
pub cached_formula_value: Option<String>,
/// Per-run formatting when the cell's string is rich text. When present,
/// `value` holds the concatenated plain text and the cell is written as a
/// rich string; when None, the string is a plain `<t>`.
pub rich_text: Option<crate::rich_text::RichText>,
}
impl CellData {
/// Create empty cell data.
pub fn new() -> Self {
Self::default()
}
/// Create cell data with a value.
pub fn with_value(value: CellValue) -> Self {
CellData {
value,
..Default::default()
}
}
}
/// Sheet visibility as stored on the workbook.xml `<sheet state>` attribute.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SheetVisibility {
/// Shown in the tab bar (default).
#[default]
Visible,
/// Hidden, but can be unhidden from the Excel UI.
Hidden,
/// Hidden and only unhideable through VBA / the object model.
VeryHidden,
}
impl SheetVisibility {
/// Attribute value for workbook.xml.
pub fn as_str(&self) -> &'static str {
match self {
SheetVisibility::Visible => "visible",
SheetVisibility::Hidden => "hidden",
SheetVisibility::VeryHidden => "veryHidden",
}
}
/// Parse the workbook.xml attribute value; unknown values load as Visible.
pub fn from_attr(value: &str) -> Self {
match value {
"hidden" => SheetVisibility::Hidden,
"veryHidden" => SheetVisibility::VeryHidden,
_ => SheetVisibility::Visible,
}
}
}
/// Data validation rule for a cell.
#[derive(Clone, Debug)]
pub struct DataValidation {
/// Type: whole, decimal, list, date, time, textLength, custom.
pub validation_type: String,
/// Comparison operator: between, notBetween, equal, notEqual, greaterThan,
/// lessThan, greaterThanOrEqual, lessThanOrEqual. None means Excel's
/// default, "between".
pub operator: Option<String>,
/// First formula/value constraint.
pub formula1: Option<String>,
/// Second formula/value constraint (for between/notBetween).
pub formula2: Option<String>,
/// Severity of the error dialog: stop, warning, or information.
pub error_style: Option<String>,
/// Allow blank values.
pub allow_blank: bool,
/// Show error message on invalid input.
pub show_error: bool,
/// Error dialog title.
pub error_title: Option<String>,
/// Error message text.
pub error_message: Option<String>,
/// Show input message when cell is selected.
pub show_input: bool,
/// Input prompt title.
pub prompt_title: Option<String>,
/// Input prompt message.
pub prompt_message: Option<String>,
/// Full sqref the rule applies to (may span multiple cells/ranges).
/// When None, the rule applies to the single cell it is keyed under.
pub sqref: Option<String>,
}
impl Default for DataValidation {
fn default() -> Self {
DataValidation {
validation_type: "whole".to_string(),
operator: None,
formula1: None,
formula2: None,
error_style: None,
allow_blank: true,
show_error: true,
error_title: None,
error_message: None,
show_input: true,
prompt_title: None,
prompt_message: None,
sqref: None,
}
}
}
/// Worksheet protection settings.
#[derive(Clone, Debug, Default)]
pub struct WorksheetProtection {
/// Sheet protection enabled.
pub sheet: bool,
/// Plaintext password; hashed with the legacy Excel verifier on save.
pub password: Option<String>,
/// Pre-hashed password verifier loaded from an existing file.
/// Takes precedence over `password` on save so a loaded hash is never re-hashed.
pub password_hash: Option<String>,
/// Allow selecting locked cells.
pub select_locked_cells: bool,
/// Allow selecting unlocked cells.
pub select_unlocked_cells: bool,
/// Allow formatting cells.
pub format_cells: bool,
/// Allow formatting columns.
pub format_columns: bool,
/// Allow formatting rows.
pub format_rows: bool,
/// Allow inserting columns.
pub insert_columns: bool,
/// Allow inserting rows.
pub insert_rows: bool,
/// Allow inserting hyperlinks.
pub insert_hyperlinks: bool,
/// Allow deleting columns.
pub delete_columns: bool,
/// Allow deleting rows.
pub delete_rows: bool,
/// Allow sorting.
pub sort: bool,
/// Allow using autofilter.
pub auto_filter: bool,
/// Allow editing pivot tables.
pub pivot_tables: bool,
/// Allow editing objects.
pub objects: bool,
/// Allow editing scenarios.
pub scenarios: bool,
}
/// Represents a worksheet in an Excel workbook.
#[derive(Clone, Debug)]
pub struct Worksheet {
/// Worksheet title/name.
pub title: String,
/// Cell data indexed by packed (row, column) key - both 1-indexed.
pub cells: CellMap,
/// Merged cell ranges as (start_coord, end_coord) strings.
pub merged_cells: Vec<(String, String)>,
/// Column widths indexed by column number.
pub column_dimensions: HashMap<u32, f64>,
/// Row heights indexed by row number.
pub row_dimensions: HashMap<u32, f64>,
/// Data validations indexed by (row, column).
pub data_validations: HashMap<(u32, u32), DataValidation>,
/// Sheet protection settings.
pub protection: Option<WorksheetProtection>,
/// Maximum row with data (for optimization).
pub max_row: u32,
/// Maximum column with data (for optimization).
pub max_column: u32,
/// AutoFilter configuration.
pub auto_filter: Option<AutoFilter>,
/// Conditional formatting rules.
pub conditional_formatting: Vec<ConditionalFormatting>,
/// Excel Tables (ListObjects).
pub tables: Vec<Table>,
/// Charts anchored on this worksheet.
pub charts: Vec<crate::chart::Chart>,
/// Images embedded on this worksheet.
pub images: Vec<crate::image::Image>,
/// Pivot-table relationships preserved from a loaded file as
/// (relationship id, type URI, target), so pivot tables anchored on this
/// sheet survive a save. Not modeled; preserved verbatim.
pub pivot_rels: Vec<(String, String, String)>,
/// Page setup and print settings.
pub page_setup: Option<PageSetup>,
/// Freeze panes anchor cell (e.g. "B2"); rows above and columns left of it stay frozen.
pub freeze_panes: Option<String>,
/// Sheet visibility (visible / hidden / veryHidden).
pub visibility: SheetVisibility,
/// Stable identity within the owning workbook. Assigned by the workbook
/// (never reused), so handles survive sheet removal, reordering, and
/// renames. 0 means the worksheet is not attached to a workbook.
pub uid: u64,
}
impl Worksheet {
/// Create a new worksheet with the given title.
pub fn new<S: Into<String>>(title: S) -> Self {
Worksheet {
title: title.into(),
cells: CellMap::default(),
merged_cells: Vec::new(),
column_dimensions: HashMap::new(),
row_dimensions: HashMap::new(),
data_validations: HashMap::new(),
protection: None,
max_row: 0,
max_column: 0,
auto_filter: None,
conditional_formatting: Vec::new(),
tables: Vec::new(),
charts: Vec::new(),
images: Vec::new(),
pivot_rels: Vec::new(),
page_setup: None,
freeze_panes: None,
visibility: SheetVisibility::default(),
uid: 0,
}
}
/// Freeze panes at the given anchor cell (e.g. "B2"). Pass `None` to unfreeze.
pub fn set_freeze_panes(&mut self, cell: Option<String>) {
self.freeze_panes = cell;
}
/// Set an AutoFilter for this worksheet.
pub fn set_auto_filter(&mut self, auto_filter: AutoFilter) {
self.auto_filter = Some(auto_filter);
}
/// Add a conditional formatting rule.
pub fn add_conditional_formatting(&mut self, cf: ConditionalFormatting) {
self.conditional_formatting.push(cf);
}
/// Add an Excel Table.
pub fn add_table(&mut self, table: Table) {
self.tables.push(table);
}
/// Add a chart anchored on this worksheet.
pub fn add_chart(&mut self, chart: crate::chart::Chart) {
self.charts.push(chart);
}
/// Add an image embedded on this worksheet.
pub fn add_image(&mut self, image: crate::image::Image) {
self.images.push(image);
}
/// Set page setup.
pub fn set_page_setup(&mut self, page_setup: PageSetup) {
self.page_setup = Some(page_setup);
}
/// Get the worksheet title.
pub fn title(&self) -> &str {
&self.title
}
/// Set the worksheet title.
pub fn set_title<S: Into<String>>(&mut self, title: S) {
self.title = title.into();
}
/// Get cell data at the specified row and column (1-indexed).
pub fn get_cell(&self, row: u32, column: u32) -> Option<&CellData> {
self.cells.get(&cell_key(row, column))
}
/// Get mutable cell data at the specified row and column (1-indexed).
pub fn get_cell_mut(&mut self, row: u32, column: u32) -> Option<&mut CellData> {
self.cells.get_mut(&cell_key(row, column))
}
/// Get the cell value at the specified position.
pub fn get_cell_value(&self, row: u32, column: u32) -> Option<&CellValue> {
self.cells.get(&cell_key(row, column)).map(|cd| &cd.value)
}
/// Set a cell value at the specified row and column (1-indexed).
pub fn set_cell_value<V: Into<CellValue>>(&mut self, row: u32, column: u32, value: V) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
cell_data.value = value.into();
self.update_dimensions(row, column);
}
/// Set a rich-text value on a cell. The cell's plain value becomes the
/// concatenated run text and the runs are preserved (and written as a rich
/// string on save).
pub fn set_cell_rich_text(&mut self, row: u32, column: u32, rich: crate::rich_text::RichText) {
let plain = rich.plain();
let cell = self.cells.entry(cell_key(row, column)).or_default();
cell.value = CellValue::String(Arc::from(plain.as_str()));
cell.data_type = Some("s");
cell.rich_text = Some(rich);
self.update_dimensions(row, column);
}
/// Get a mutable reference to a cell, creating it if it doesn't exist.
pub fn get_or_create_cell_mut(&mut self, row: u32, column: u32) -> &mut CellData {
self.update_dimensions(row, column);
self.cells.entry(cell_key(row, column)).or_default()
}
/// Set complete cell data at the specified position.
pub fn set_cell_data(&mut self, row: u32, column: u32, data: CellData) {
self.cells.insert(cell_key(row, column), data);
self.update_dimensions(row, column);
}
/// Set a formula in a cell.
pub fn set_cell_formula<S: Into<String>>(&mut self, row: u32, column: u32, formula: S) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
cell_data.value = CellValue::Formula(formula.into());
self.update_dimensions(row, column);
}
/// Set a cell's hyperlink.
pub fn set_cell_hyperlink(&mut self, row: u32, column: u32, url: String) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
cell_data.hyperlink = Some(url);
self.update_dimensions(row, column);
}
/// Set a cell's comment.
pub fn set_cell_comment(&mut self, row: u32, column: u32, comment: String) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
cell_data.comment = Some(comment);
self.update_dimensions(row, column);
}
/// Set a cell's style.
pub fn set_cell_style(&mut self, row: u32, column: u32, style: CellStyle) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
cell_data.style = Some(Arc::new(style));
// Invalidate any loaded xf index so the new style is re-resolved on save
cell_data.style_index = None;
self.update_dimensions(row, column);
}
/// Set a cell's font, merging with any existing style on the cell.
pub fn set_cell_font(&mut self, row: u32, column: u32, font: crate::style::Font) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
let mut style = cell_data
.style
.as_deref()
.cloned()
.unwrap_or_else(CellStyle::new);
style.font = Some(font);
cell_data.style = Some(Arc::new(style));
cell_data.style_index = None;
self.update_dimensions(row, column);
}
/// Set a cell's alignment, merging with any existing style on the cell.
pub fn set_cell_alignment(
&mut self,
row: u32,
column: u32,
alignment: crate::style::Alignment,
) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
let mut style = cell_data
.style
.as_deref()
.cloned()
.unwrap_or_else(CellStyle::new);
style.alignment = Some(alignment);
cell_data.style = Some(Arc::new(style));
cell_data.style_index = None;
self.update_dimensions(row, column);
}
/// Set a cell's number format.
pub fn set_cell_number_format<S: AsRef<str>>(&mut self, row: u32, column: u32, format: S) {
let cell_data = self.cells.entry(cell_key(row, column)).or_default();
cell_data.number_format = Some(Arc::from(format.as_ref()));
// Invalidate any loaded xf index so the format is re-resolved on save
cell_data.style_index = None;
self.update_dimensions(row, column);
}
/// Add a merged cell range.
pub fn add_merged_cell<S: Into<String>>(&mut self, start: S, end: S) {
self.merged_cells.push((start.into(), end.into()));
}
/// Merge cells in a range (e.g., "A1:B2").
pub fn merge_cells(&mut self, range: &str) {
if let Some(colon_pos) = range.find(':') {
let start = range[..colon_pos].to_string();
let end = range[colon_pos + 1..].to_string();
self.merged_cells.push((start, end));
}
}
/// Unmerge cells in a range.
pub fn unmerge_cells(&mut self, range: &str) {
if let Some(colon_pos) = range.find(':') {
let start = range[..colon_pos].to_string();
let end = range[colon_pos + 1..].to_string();
self.merged_cells
.retain(|(s, e)| !(s == &start && e == &end));
}
}
/// Set column width.
pub fn set_column_width(&mut self, column: u32, width: f64) {
self.column_dimensions.insert(column, width);
}
/// Get column width.
pub fn get_column_width(&self, column: u32) -> Option<f64> {
self.column_dimensions.get(&column).copied()
}
/// Estimate the width (in Excel character units) needed to show a column's
/// content, or `None` if the column has no populated cells.
///
/// This is an approximation, not pixel-perfect: Excel measures actual glyph
/// widths, whereas this counts characters of the *displayed* string (the
/// value rendered under its number format), scales roughly by font size and
/// bold, adds padding, and clamps to Excel's maximum. Good enough for the
/// common "make the columns readable" need.
pub fn estimate_column_width(&self, column: u32) -> Option<f64> {
// Excel's default column width plus padding for cell margins/gridline.
const PADDING: f64 = 2.0;
// Excel's hard maximum column width.
const MAX_WIDTH: f64 = 255.0;
let mut max_units: f64 = 0.0;
let mut saw_cell = false;
for (key, cell) in &self.cells {
let (_, col) = decode_cell_key(*key);
if col != column {
continue;
}
if matches!(cell.value, CellValue::Empty) && cell.rich_text.is_none() {
continue;
}
saw_cell = true;
// The effective format code may live on the interned per-cell field
// (set through the core API and on load) or on the cell's style (set
// through the styled-cell API).
let style_format = cell.style.as_ref().and_then(|s| s.number_format.as_deref());
let code = cell
.number_format
.as_deref()
.or(style_format)
.unwrap_or("General");
let display = crate::numfmt::format_value(&cell.value, code);
// A wrapped/multi-line string is only as wide as its longest line.
let longest_line = display
.split('\n')
.map(|line| line.chars().count())
.max()
.unwrap_or(0) as f64;
let mut units = longest_line;
if let Some(style) = &cell.style {
if let Some(font) = &style.font {
if let Some(size) = font.size {
if size > 0.0 {
units *= size / 11.0;
}
}
if font.bold {
units *= 1.05;
}
}
}
max_units = max_units.max(units);
}
if !saw_cell {
return None;
}
Some((max_units + PADDING).min(MAX_WIDTH))
}
/// Size a column to fit its content and return the width set. Does nothing
/// and returns `None` when the column has no populated cells.
pub fn auto_fit_column(&mut self, column: u32) -> Option<f64> {
let width = self.estimate_column_width(column)?;
self.set_column_width(column, width);
Some(width)
}
/// Auto-fit every column that has content.
pub fn auto_fit_all(&mut self) {
let mut columns: Vec<u32> = self
.cells
.keys()
.map(|key| decode_cell_key(*key).1)
.collect();
columns.sort_unstable();
columns.dedup();
for column in columns {
self.auto_fit_column(column);
}
}
/// Set row height.
pub fn set_row_height(&mut self, row: u32, height: f64) {
self.row_dimensions.insert(row, height);
}
/// Get row height.
pub fn get_row_height(&self, row: u32) -> Option<f64> {
self.row_dimensions.get(&row).copied()
}
/// Add data validation to a cell.
pub fn add_data_validation(&mut self, row: u32, column: u32, validation: DataValidation) {
self.data_validations.insert((row, column), validation);
}
/// Get data validation for a cell.
pub fn get_data_validation(&self, row: u32, column: u32) -> Option<&DataValidation> {
self.data_validations.get(&(row, column))
}
/// Enable sheet protection.
pub fn enable_protection(&mut self, password: Option<String>) {
self.protection = Some(WorksheetProtection {
sheet: true,
password,
..Default::default()
});
}
/// Disable sheet protection.
pub fn disable_protection(&mut self) {
self.protection = None;
}
/// Check if sheet is protected.
pub fn is_protected(&self) -> bool {
self.protection.as_ref().is_some_and(|p| p.sheet)
}
/// Get the maximum row number with data.
pub fn max_row(&self) -> u32 {
self.max_row
}
/// Get the maximum column number with data.
pub fn max_column(&self) -> u32 {
self.max_column
}
/// Get dimensions as (min_row, min_col, max_row, max_col).
pub fn dimensions(&self) -> (u32, u32, u32, u32) {
if self.cells.is_empty() {
return (1, 1, 1, 1);
}
let mut min_row = u32::MAX;
let mut min_col = u32::MAX;
let mut max_row = 0;
let mut max_col = 0;
for &key in self.cells.keys() {
let (row, col) = decode_cell_key(key);
min_row = min_row.min(row);
min_col = min_col.min(col);
max_row = max_row.max(row);
max_col = max_col.max(col);
}
(min_row, min_col, max_row, max_col)
}
/// Iterate over all cells in row-major order.
pub fn iter_cells(&self) -> impl Iterator<Item = ((u32, u32), &CellData)> {
let mut cells: Vec<_> = self.cells.iter().map(|(k, v)| (*k, v)).collect();
cells.sort_by_key(|(k, _)| decode_cell_key(*k));
cells.into_iter().map(|(k, v)| (decode_cell_key(k), v))
}
/// Iterate over the populated cells of one row, in column order.
///
/// Probes the row's columns by key rather than scanning the whole cell map:
/// filtering and sorting every cell to serve one row made row-by-row
/// iteration O(rows * total_cells).
pub fn iter_row(&self, row: u32) -> impl Iterator<Item = (u32, &CellData)> + '_ {
(1..=self.max_column).filter_map(move |col| {
self.cells
.get(&cell_key(row, col))
.map(|cell_data| (col, cell_data))
})
}
/// Update max_row and max_column.
fn update_dimensions(&mut self, row: u32, column: u32) {
self.max_row = self.max_row.max(row);
self.max_column = self.max_column.max(column);
}
/// Insert `amount` blank rows before row `idx` (1-based). Cells at or below
/// `idx` shift down; merged ranges, data validations, conditional
/// formatting, tables, and the autofilter/freeze anchors move with them.
/// Formula text is left unchanged, matching openpyxl.
pub fn insert_rows(&mut self, idx: u32, amount: u32) {
if amount > 0 && idx >= 1 {
self.apply_shift(Shift::Insert { at: idx, amount }, true);
}
}
/// Delete `amount` rows starting at row `idx` (1-based).
pub fn delete_rows(&mut self, idx: u32, amount: u32) {
if amount > 0 && idx >= 1 {
self.apply_shift(Shift::Delete { at: idx, amount }, true);
}
}
/// Insert `amount` blank columns before column `idx` (1-based).
pub fn insert_columns(&mut self, idx: u32, amount: u32) {
if amount > 0 && idx >= 1 {
self.apply_shift(Shift::Insert { at: idx, amount }, false);
}
}
/// Delete `amount` columns starting at column `idx` (1-based).
pub fn delete_columns(&mut self, idx: u32, amount: u32) {
if amount > 0 && idx >= 1 {
self.apply_shift(Shift::Delete { at: idx, amount }, false);
}
}
/// Apply a row or column insert/delete to every position-bearing part of
/// the sheet. `is_row` selects the axis.
fn apply_shift(&mut self, shift: Shift, is_row: bool) {
let map_pos = |row: u32, col: u32| -> Option<(u32, u32)> {
if is_row {
shift.map(row).map(|r| (r, col))
} else {
shift.map(col).map(|c| (row, c))
}
};
// Cells (with their per-cell styles/hyperlinks/comments): rebuild the
// map with shifted keys, dropping any cell in a deleted band.
let mut new_cells = CellMap::default();
new_cells.reserve(self.cells.len());
for (key, data) in self.cells.drain() {
let (row, col) = decode_cell_key(key);
if let Some((r, c)) = map_pos(row, col) {
new_cells.insert(cell_key(r, c), data);
}
}
self.cells = new_cells;
// Row heights / column widths: shift keys on the affected axis only.
if is_row {
self.row_dimensions = shift_dim_keys(&self.row_dimensions, shift);
} else {
self.column_dimensions = shift_dim_keys(&self.column_dimensions, shift);
}
// Merged ranges: move/grow/shrink; drop if collapsed to nothing or to a
// single cell (no longer a merge).
self.merged_cells
.retain_mut(|(s, e)| match shift_merge(s, e, shift, is_row) {
Some((ns, ne)) => {
*s = ns;
*e = ne;
true
}
None => false,
});
// Data validations: shift the keying cell and each rule's sqref.
let mut new_dv = HashMap::new();
for ((row, col), mut dv) in std::mem::take(&mut self.data_validations) {
if let Some(pos) = map_pos(row, col) {
if let Some(ref sq) = dv.sqref {
dv.sqref = shift_sqref(sq, shift, is_row);
}
new_dv.insert(pos, dv);
}
}
self.data_validations = new_dv;
// Range-bearing features.
self.conditional_formatting.retain_mut(|cf| {
match shift_range_str(&cf.range, shift, is_row) {
Some(r) => {
cf.range = r;
true
}
None => false,
}
});
self.tables
.retain_mut(|t| match shift_range_str(&t.range, shift, is_row) {
Some(r) => {
t.range = r;
true
}
None => false,
});
if let Some(af) = self.auto_filter.as_mut() {
if let Some(r) = shift_range_str(&af.range, shift, is_row) {
af.range = r;
}
}
if let Some(anchor) = self.freeze_panes.take() {
self.freeze_panes = shift_coord_str(&anchor, shift, is_row);
}
self.recompute_dimensions();
}
/// Recompute max_row/max_column by scanning the (already shifted) cell map.
fn recompute_dimensions(&mut self) {
let (mut max_row, mut max_col) = (0, 0);
for &key in self.cells.keys() {
let (r, c) = decode_cell_key(key);
max_row = max_row.max(r);
max_col = max_col.max(c);
}
self.max_row = max_row;
self.max_column = max_col;
}
}
/// A row or column insert/delete on one axis; positions are 1-based.
#[derive(Clone, Copy)]
enum Shift {
Insert { at: u32, amount: u32 },
Delete { at: u32, amount: u32 },
}
impl Shift {
/// New position of a single cell/dimension, or None if it was deleted.
fn map(self, p: u32) -> Option<u32> {
match self {
Shift::Insert { at, amount } => Some(if p >= at { p + amount } else { p }),
Shift::Delete { at, amount } => {
if p < at {
Some(p)
} else if p < at + amount {
None
} else {
Some(p - amount)
}
}
}
}
/// New start endpoint of a range; a delete clamps up to the first surviving
/// position so a range straddling the gap shrinks rather than vanishes.
fn map_start(self, a: u32) -> u32 {
match self {
Shift::Insert { at, amount } => {
if a >= at {
a + amount
} else {
a
}
}
Shift::Delete { at, amount } => {
if a < at {
a
} else if a < at + amount {
at
} else {
a - amount
}
}
}
}
/// New end endpoint of a range; a delete clamps down to the last surviving
/// position before the gap.
fn map_end(self, b: u32) -> u32 {
match self {
Shift::Insert { at, amount } => {
if b >= at {
b + amount
} else {
b
}
}
Shift::Delete { at, amount } => {
if b < at {
b
} else if b < at + amount {
at.saturating_sub(1)
} else {
b - amount
}
}
}
}
}
/// Shift an `"A1"` coordinate on one axis; None if the cell was deleted.
fn shift_coord_str(coord: &str, shift: Shift, is_row: bool) -> Option<String> {
let (row, col) = crate::utils::parse_coordinate(coord).ok()?;
let (nr, nc) = if is_row {
(shift.map(row)?, col)
} else {
(row, shift.map(col)?)
};
Some(crate::utils::coordinate_from_row_col(nr, nc))
}
/// Shift a merged range's `(start, end)` coordinates; None if it collapses to
/// nothing or to a single cell (no longer a merge).
fn shift_merge(s: &str, e: &str, shift: Shift, is_row: bool) -> Option<(String, String)> {
let (r1, c1) = crate::utils::parse_coordinate(s).ok()?;
let (r2, c2) = crate::utils::parse_coordinate(e).ok()?;
let (nr1, nc1, nr2, nc2) = if is_row {
(shift.map_start(r1), c1, shift.map_end(r2), c2)
} else {
(r1, shift.map_start(c1), r2, shift.map_end(c2))
};
if nr1 > nr2 || nc1 > nc2 || (nr1 == nr2 && nc1 == nc2) {
return None;
}
Some((
crate::utils::coordinate_from_row_col(nr1, nc1),
crate::utils::coordinate_from_row_col(nr2, nc2),
))
}
/// Shift a range string `"A1:B2"` (or a bare `"A1"`) on one axis; None if the
/// range was entirely deleted. A range that collapses to one cell is returned
/// as a bare coordinate.
fn shift_range_str(range: &str, shift: Shift, is_row: bool) -> Option<String> {
let (s, e) = match range.split_once(':') {
Some((a, b)) => (a.trim(), b.trim()),
None => (range.trim(), range.trim()),
};
let (r1, c1) = crate::utils::parse_coordinate(s).ok()?;
let (r2, c2) = crate::utils::parse_coordinate(e).ok()?;
let (nr1, nc1, nr2, nc2) = if is_row {
(shift.map_start(r1), c1, shift.map_end(r2), c2)
} else {
(r1, shift.map_start(c1), r2, shift.map_end(c2))
};
if nr1 > nr2 || nc1 > nc2 {
return None;
}
let start = crate::utils::coordinate_from_row_col(nr1, nc1);
if (nr1, nc1) == (nr2, nc2) {
Some(start)
} else {
Some(format!(
"{}:{}",
start,
crate::utils::coordinate_from_row_col(nr2, nc2)
))
}
}
/// Shift a whitespace-separated multi-range sqref; None if every range was
/// deleted.
fn shift_sqref(sqref: &str, shift: Shift, is_row: bool) -> Option<String> {
let parts: Vec<String> = sqref
.split_whitespace()
.filter_map(|r| shift_range_str(r, shift, is_row))
.collect();
if parts.is_empty() {
None
} else {
Some(parts.join(" "))
}
}
/// Shift the keys of a row/column dimension map, dropping deleted lines.
fn shift_dim_keys(dims: &HashMap<u32, f64>, shift: Shift) -> HashMap<u32, f64> {
let mut out = HashMap::with_capacity(dims.len());
for (&k, &v) in dims {
if let Some(nk) = shift.map(k) {
out.insert(nk, v);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_worksheet_new() {
let ws = Worksheet::new("Sheet1");
assert_eq!(ws.title(), "Sheet1");
assert!(ws.cells.is_empty());
}
/// iter_row yields only the populated cells of the requested row, in
/// column order, and skips gaps.
#[test]
fn test_iter_row_returns_populated_cells_in_column_order() {
let mut ws = Worksheet::new("S");
ws.set_cell_value(2, 3, CellValue::Number(3.0));
ws.set_cell_value(2, 1, CellValue::Number(1.0));
ws.set_cell_value(1, 2, CellValue::Number(99.0)); // different row
ws.set_cell_value(2, 6, CellValue::Number(6.0));
let row: Vec<(u32, f64)> = ws
.iter_row(2)
.map(|(col, cell)| match cell.value {
CellValue::Number(n) => (col, n),
_ => panic!("expected a number"),
})
.collect();
assert_eq!(row, vec![(1, 1.0), (3, 3.0), (6, 6.0)]);
assert_eq!(ws.iter_row(3).count(), 0, "empty row yields nothing");
}
#[test]
fn test_set_cell_value() {
let mut ws = Worksheet::new("Sheet1");
ws.set_cell_value(1, 1, "Hello");
let val = ws.get_cell_value(1, 1);
assert!(matches!(val, Some(CellValue::String(s)) if s.as_ref() == "Hello"));
assert_eq!(ws.max_row(), 1);
assert_eq!(ws.max_column(), 1);
}
#[test]
fn test_set_cell_formula() {
let mut ws = Worksheet::new("Sheet1");
ws.set_cell_formula(1, 1, "SUM(A1:A10)");
let val = ws.get_cell_value(1, 1);
assert!(matches!(val, Some(CellValue::Formula(f)) if f == "SUM(A1:A10)"));
}
#[test]
fn test_merged_cells() {
let mut ws = Worksheet::new("Sheet1");
ws.merge_cells("A1:B2");
assert_eq!(ws.merged_cells.len(), 1);
ws.unmerge_cells("A1:B2");
assert!(ws.merged_cells.is_empty());
}
#[test]
fn test_column_dimensions() {
let mut ws = Worksheet::new("Sheet1");
ws.set_column_width(1, 15.0);
assert_eq!(ws.get_column_width(1), Some(15.0));
assert_eq!(ws.get_column_width(2), None);
}
#[test]
fn test_row_dimensions() {
let mut ws = Worksheet::new("Sheet1");
ws.set_row_height(1, 20.0);
assert_eq!(ws.get_row_height(1), Some(20.0));
assert_eq!(ws.get_row_height(2), None);
}
#[test]
fn test_protection() {
let mut ws = Worksheet::new("Sheet1");
assert!(!ws.is_protected());
ws.enable_protection(Some("password".to_string()));
assert!(ws.is_protected());
ws.disable_protection();
assert!(!ws.is_protected());
}
#[test]
fn test_dimensions() {
let mut ws = Worksheet::new("Sheet1");
ws.set_cell_value(2, 3, "A");
ws.set_cell_value(5, 1, "B");
let (min_r, min_c, max_r, max_c) = ws.dimensions();
assert_eq!((min_r, min_c), (2, 1));
assert_eq!((max_r, max_c), (5, 3));
}
}