-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpreadsheetTool.cs
More file actions
2981 lines (2741 loc) · 149 KB
/
Copy pathSpreadsheetTool.cs
File metadata and controls
2981 lines (2741 loc) · 149 KB
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
using Aspose.Cells_FOSS;
using System.Diagnostics;
using System.Globalization;
using System.IO.Compression;
namespace AIOrchestrator.API
{
/// <summary>
/// Spreadsheet (XLSX) operations for agent use: open/create, cells, ranges, styles, charts, tables.
/// </summary>
public class SpreadsheetTool : BaseAgentTool, IDisposable, IFileTool
{
private Workbook? _workbook;
private string _filePath = string.Empty;
/// <summary>True when the in-memory workbook differs from the file on disk. Lets Dispose
/// skip the redundant second save when the agent already called Save explicitly.</summary>
private bool _dirty;
/// <summary>Columns the agent wrote to or styled this session, per worksheet. Only these
/// get the bestFit flag at save: a column the USER set up (width or plain content) is
/// never touched unless the agent works on it.</summary>
private readonly Dictionary<string, HashSet<int>> _touchedCols = new();
/// <summary>Columns that will receive the OOXML bestFit flag (auto width computed by the
/// opening application) at save, per worksheet. Populated by the deterministic auto-format
/// pass right before persisting.</summary>
private readonly Dictionary<string, HashSet<int>> _bestFitCols = new();
/// <summary>Guard for agent-supplied ranges: the tool must never let a huge range
/// (e.g. "A1:XFD1048576") allocate unbounded memory or hang the session.</summary>
private const int MaxCellArea = 1_000_000;
/// <summary>
/// Parameterless constructor for agent activation. Call <see cref="Open"/> or <see cref="Create"/>
/// before using other methods.
/// </summary>
public SpreadsheetTool()
{
}
/// <summary>
/// Opens an existing XLSX workbook for editing.
/// </summary>
/// <param name="filePath">
/// Path to an existing .xlsx file, Unix style relative to the workspace root (leading
/// "/", e.g. "/folder/file.xlsx").
/// </param>
public SpreadsheetTool(string filePath)
{
Open(filePath);
}
/// <summary>
/// Opens an existing XLSX workbook and replaces the current one.
/// Call this when the agent already has an instance (created via parameterless constructor)
/// and needs to load a specific file.
/// </summary>
/// <param name="filePath">Path to an existing .xlsx file (Unix style, e.g. "/folder/file.xlsx").</param>
/// <returns>"true", or "Error: …" when the file cannot be opened.</returns>
public string Open(string filePath)
{
try
{
_workbook?.Dispose();
_filePath = SandboxPath.Resolve(filePath);
_workbook = new Workbook(_filePath);
_touchedCols.Clear();
_bestFitCols.Clear();
_dirty = false;
Log.LogStep($"SpreadsheetTool.Open: opened '{_filePath}'");
return "true";
}
catch (Exception ex)
{
Log.LogStep($"SpreadsheetTool.Open: failed '{filePath}': {ex.Message}");
return $"Error: {ex.Message}";
}
}
/// <summary>
/// Creates a new XLSX workbook with one default worksheet ("Sheet1") on THIS instance.
/// Must be an instance method (not a static factory): the agent loop keeps ONE shared
/// instance in its agents dictionary, so a static Create returning a brand-new agent
/// discarded the workbook and every later edit failed with a NullReferenceException.
/// </summary>
/// <param name="filePath">
/// Path where the new .xlsx file will be saved, Unix style relative to the workspace
/// root (e.g. "/folder/file.xlsx").
/// </param>
/// <returns>"true", or "Error: …" when the file cannot be created.</returns>
public string Create(string filePath)
{
try
{
var resolved = SandboxPath.Resolve(filePath);
_workbook?.Dispose();
_workbook = new Workbook();
_touchedCols.Clear();
_bestFitCols.Clear();
_workbook.Save(resolved);
_filePath = resolved;
_dirty = false;
Log.LogStep($"SpreadsheetTool.Create: created '{resolved}'");
return $"Workbook created at '{SandboxPath.ToAgent(resolved)}'.";
}
catch (Exception ex)
{
return $"Error: {ex.Message}";
}
}
/// <summary>
/// Writes all pending changes to the current file path — an explicit checkpoint.
/// (Changes are also persisted automatically when the tool is disposed, so the file
/// on disk always reflects the final session state.)
/// A save that would produce an unreadable file is rejected: the previous file is left
/// untouched and no version is created.
/// The new content becomes a new version in the workspace git repo (rollback via GitTool.restore).
/// </summary>
/// <returns>A message describing the result: the new version id, or an error when the
/// save was rejected.</returns>
public string Save()
{
if (_workbook == null) return "No changes to save — no workbook is open.";
if (!_dirty) return "No changes to save — the workbook is unchanged since the last save.";
ApplyDeterministicAutoFormat();
var validationError = PersistValidated(_filePath);
if (validationError != null)
{
Log.LogStep($"SpreadsheetTool.Save: REJECTED — {validationError}");
return "Error: save rejected — the workbook could not be saved correctly; the previous file and the last git version are untouched.";
}
var versionId = GitSupport.Snapshot(_filePath, "SpreadsheetTool save");
_dirty = false;
Log.LogStep($"SpreadsheetTool.Save: saved to '{_filePath}', version='{versionId}'");
var agentPath = SandboxPath.ToAgent(_filePath);
return versionId != null
? $"Workbook saved to '{agentPath}'. New version: {versionId}. (Rollback via GitTool.restore.)"
: $"Workbook saved to '{agentPath}'. (No changes detected.)";
}
/// <summary>
/// Writes all pending changes to a new file path.
/// Subsequent Save() calls will use the new path.
/// A save that would produce an unreadable file is rejected: the target file is not created.
/// The new content becomes a new version in the workspace git repo.
/// </summary>
/// <param name="newFilePath">Path for the new .xlsx file, Unix style relative to the workspace root (e.g. "/folder/file.xlsx").</param>
/// <returns>A message describing the result, or an error when the save was rejected.</returns>
public string SaveAs(string newFilePath)
{
if (_workbook == null) return "No changes to save — no workbook is open.";
var resolved = SandboxPath.Resolve(newFilePath);
ApplyDeterministicAutoFormat();
var validationError = PersistValidated(resolved);
if (validationError != null)
{
Log.LogStep($"SpreadsheetTool.SaveAs: REJECTED — {validationError}");
return "Error: save rejected — the workbook could not be saved correctly; the target file was not created.";
}
_filePath = resolved;
var versionId = GitSupport.Snapshot(_filePath, "SpreadsheetTool save as");
_dirty = false;
Log.LogStep($"SpreadsheetTool.SaveAs: saved to '{_filePath}', version='{versionId}'");
var agentPath = SandboxPath.ToAgent(resolved);
return versionId != null
? $"Workbook saved as '{agentPath}'. New version: {versionId}."
: $"Workbook saved as '{agentPath}'.";
}
/// <summary>Reverts the OPEN workbook to a version from the workspace git repo (list them with
/// GitTool.history). The current state is saved as a new version first (the rollback is
/// reversible), then the file is overwritten and the workbook is reloaded. Use this when the
/// workbook is open in this tool; GitTool.restore handles files that are not open.</summary>
/// <param name="versionId">Version to restore, from GitTool.history().</param>
/// <returns>Descriptive result message.</returns>
public string Restore(string versionId)
{
if (_workbook == null) return "No workbook is open. Nothing to restore.";
try
{
_workbook.Dispose(); // release the open handle so the file can be overwritten
var message = GitSupport.Restore(versionId, _filePath);
_workbook = new Workbook(_filePath);
_dirty = false; // reloaded state matches the file on disk
return message;
}
catch (Exception ex)
{
// Never leave the tool with a null workbook: reload the file (git restores it
// atomically per file) or fall back to a blank workbook so later calls keep
// working; the agent still gets a descriptive error.
try { if (_workbook == null) _workbook = new Workbook(_filePath); }
catch { _workbook = new Workbook(); _filePath = string.Empty; }
_dirty = true;
return $"Error: Restore failed: {ex.Message}";
}
}
/// <summary>
/// Explicit interface implementation — NOT an agent tool (the orchestrator disposes
/// agents automatically when the loop ends). Persists any unsaved changes first so the
/// file on disk always reflects the final session state, then releases the workbook.
/// A save that fails is not committed: the last good file stays on disk.
/// </summary>
void IDisposable.Dispose()
{
try
{
if (_workbook != null && !string.IsNullOrEmpty(_filePath) && _dirty)
{
ApplyDeterministicAutoFormat();
var validationError = PersistValidated(_filePath);
if (validationError != null)
{
Log.LogStep($"SpreadsheetTool.Dispose: auto-save REJECTED — {validationError} (file on disk left untouched)");
}
else
{
var versionId = GitSupport.Snapshot(_filePath, "SpreadsheetTool auto-save");
_dirty = false;
Log.LogStep(versionId != null
? $"SpreadsheetTool.Dispose: auto-saved '{_filePath}' (version '{versionId}')"
: $"SpreadsheetTool.Dispose: auto-saved '{_filePath}' (no changes)");
}
}
}
catch (Exception ex)
{
Log.LogStep($"SpreadsheetTool.Dispose: auto-save failed — {ex.Message}");
}
_workbook?.Dispose();
}
/// <summary>
/// Gets the current file path of this workbook, or null if not loaded.
/// </summary>
public string? FilePath => string.IsNullOrEmpty(_filePath) ? null : _filePath;
// ──────────────────────────────────────────────
// Worksheet operations
// ──────────────────────────────────────────────
/// <summary>
/// Lists all worksheet names in the workbook, in sheet order.
/// </summary>
/// <returns>Array of sheet names.</returns>
public string[] GetSheetNames()
{
var names = new string[_workbook.Worksheets.Count];
for (int i = 0; i < names.Length; i++)
names[i] = _workbook.Worksheets[i].Name;
Log.LogStep($"SpreadsheetTool.GetSheetNames: [{string.Join(", ", names)}]");
return names;
}
/// <summary>
/// Renames an existing worksheet.
/// </summary>
/// <param name="currentName">Current worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="newName">New worksheet name.</param>
/// <returns>"true", or "Error: …" when the sheet is missing or the name is taken.</returns>
public string RenameWorksheet(string currentName, string newName)
{
if (string.IsNullOrWhiteSpace(newName)) return "Error: new worksheet name is required";
var ws = FindSheet(currentName);
if (ws == null) return $"Error: worksheet '{currentName}' not found";
if (FindSheet(newName) != null) return $"Error: worksheet '{newName}' already exists";
// Keep the per-sheet tracking with the renamed sheet.
foreach (var map in new[] { _touchedCols, _bestFitCols })
if (map.TryGetValue(currentName, out var set))
{
map.Remove(currentName);
map[newName] = set;
}
ws.Name = newName;
Log.LogStep($"SpreadsheetTool.RenameWorksheet: '{currentName}' → '{newName}'");
_dirty = true;
return "true";
}
/// <summary>
/// Shows or hides gridlines on a worksheet.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="show">True to show gridlines, false to hide them.</param>
/// <returns>"true", or "Error: …" when the sheet is missing.</returns>
public string ShowGridlines(string sheetName, bool show)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
ws.ShowGridlines = show;
Log.LogStep($"SpreadsheetTool.ShowGridlines: '{sheetName}' show={show}");
_dirty = true;
return "true";
}
/// <summary>
/// Shows or hides row and column headers (the gray 1,2,3... / A,B,C... area) on a worksheet.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="show">True to show headers, false to hide them.</param>
/// <returns>"true", or "Error: …" when the sheet is missing.</returns>
public string ShowRowColumnHeaders(string sheetName, bool show)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
ws.ShowRowColumnHeaders = show;
Log.LogStep($"SpreadsheetTool.ShowRowColumnHeaders: '{sheetName}' show={show}");
_dirty = true;
return "true";
}
/// <summary>
/// Sets the zoom percentage for a worksheet (10-400).
/// 100 = normal zoom.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="zoomPercentage">Zoom level between 10 and 400.</param>
/// <returns>"true", or "Error: …" when the sheet is missing or the zoom is out of range.</returns>
public string SetZoom(string sheetName, int zoomPercentage)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
if (zoomPercentage < 10 || zoomPercentage > 400) return $"Error: zoom must be between 10 and 400 (got {zoomPercentage})";
ws.Zoom = zoomPercentage;
Log.LogStep($"SpreadsheetTool.SetZoom: '{sheetName}' zoom={zoomPercentage}");
_dirty = true;
return "true";
}
/// <summary>
/// Protects a worksheet so its structure cannot be modified.
/// After protection, cells marked as locked (true by default) become read-only.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <returns>"true", or "Error: …" when the sheet is missing.</returns>
public string ProtectSheet(string sheetName)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
ws.Protect();
Log.LogStep($"SpreadsheetTool.ProtectSheet: '{sheetName}'");
_dirty = true;
return "true";
}
/// <summary>
/// Removes protection from a previously protected worksheet,
/// allowing edits to locked cells again.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <returns>"true", or "Error: …" when the sheet is missing.</returns>
public string UnprotectSheet(string sheetName)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
ws.Unprotect();
Log.LogStep($"SpreadsheetTool.UnprotectSheet: '{sheetName}'");
_dirty = true;
return "true";
}
/// <summary>Adds a new, empty worksheet to the workbook.</summary>
/// <param name="name">Name for the new worksheet (e.g. "Riepilogo"). Must be unique in the workbook.</param>
/// <returns>"true", or "Error: …" when the name is invalid or already taken.</returns>
public string AddWorksheet(string name)
{
try
{
_workbook.Worksheets.Add(name);
_dirty = true;
Log.LogStep($"SpreadsheetTool.AddWorksheet: added '{name}'");
return "true";
}
catch (Exception ex)
{
Log.LogStep($"SpreadsheetTool.AddWorksheet: FAILED — {ex.Message}");
return $"Error: {ex.Message}";
}
}
// ──────────────────────────────────────────────
// Cell read / write
// ──────────────────────────────────────────────
/// <summary>
/// Returns the display string value of a cell.
/// Applies number/date formatting if the cell has any.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="cellReference">Cell reference in A1 notation (e.g. "A1", "C5", "AB12").</param>
/// <returns>The cell's display value, or null if not found.</returns>
public string? GetCellValue(string sheetName, string cellReference)
{
var ws = FindSheet(sheetName);
if (ws == null || !TryParseCellRef(cellReference).Ok) return null;
return ws.Cells[cellReference]?.DisplayStringValue;
}
/// <summary>
/// Sets the value of a cell. Auto-detects numbers, booleans, dates, and strings.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="cellReference">Cell reference in A1 notation (e.g. "A1", "C5").</param>
/// <param name="value">The value to write. Parsed automatically.</param>
/// <returns>The area receipt for the written cell — sheet name, exact cell reference and
/// the stored value (feedback for the agent to verify its own work), or "Error: …" when
/// the sheet or the cell reference is invalid.</returns>
public object SetCellValue(string sheetName, string cellReference, string value)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
var p = TryParseCellRef(cellReference);
if (!p.Ok) return $"Error: {p.Error}";
MarkColumnTouched(ws.Name, p.Col);
SetCellValueAuto(ws.Cells[cellReference], value);
_dirty = true;
Log.LogStep($"SpreadsheetTool.SetCellValue: '{sheetName}'!{cellReference} = '{value}'");
return DescribeArea(ws, p.Row, p.Col, p.Row, p.Col);
}
/// <summary>
/// Gets the formula of a cell (e.g. "=SUM(A1:A10)").
/// Returns null if the cell has no formula.
/// Note: formulas are stored and round-tripped but are NOT recalculated automatically.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="cellReference">Cell reference in A1 notation (e.g. "A1").</param>
/// <returns>The formula with leading '=', or null.</returns>
public string? GetCellFormula(string sheetName, string cellReference)
{
var ws = FindSheet(sheetName);
if (ws == null || !TryParseCellRef(cellReference).Ok) return null;
var f = ws.Cells[cellReference]?.Formula;
return string.IsNullOrEmpty(f) ? null : f;
}
/// <summary>
/// Sets a formula on a cell (e.g. "=SUM(A1:A10)").
/// Formulas are stored and round-tripped but not recalculated automatically.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="cellReference">Cell reference in A1 notation (e.g. "A1").</param>
/// <param name="formula">Formula including the leading '=' (e.g. "=SUM(B2:B10)").</param>
/// <returns>The area receipt for the written cell (sheet, cell reference, formula —
/// feedback for the agent to verify its own work), or "Error: …" on invalid input.</returns>
public object SetCellFormula(string sheetName, string cellReference, string formula)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
var p = TryParseCellRef(cellReference);
if (!p.Ok) return $"Error: {p.Error}";
var cell = ws.Cells[cellReference];
if (cell == null) return $"Error: cell '{cellReference}' not found";
MarkColumnTouched(ws.Name, p.Col);
cell.Formula = formula;
Log.LogStep($"SpreadsheetTool.SetCellFormula: '{sheetName}'!{cellReference} = {formula}");
_dirty = true;
return DescribeArea(ws, p.Row, p.Col, p.Row, p.Col);
}
/// <summary>
/// Returns value, formula and type of a cell in a single call — the agent needs one
/// round-trip instead of GetCellValue + GetCellFormula + GetCellType.
/// Value is the display string; Formula is null when the cell has none.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="cellReference">Cell reference in A1 notation (e.g. "A1").</param>
/// <returns>JSON with "value", "formula" and "type" keys, or null if not found.</returns>
public string? GetCellInfo(string sheetName, string cellReference)
{
var ws = FindSheet(sheetName);
if (ws == null || !TryParseCellRef(cellReference).Ok) return null;
var cell = ws.Cells[cellReference];
if (cell == null) return null;
var f = cell.Formula;
return System.Text.Json.JsonSerializer.Serialize(new Dictionary<string, object?>
{
["value"] = cell.DisplayStringValue,
["formula"] = string.IsNullOrEmpty(f) ? null : f,
["type"] = GetCellType(sheetName, cellReference),
});
}
/// <summary>
/// Returns the underlying value type of a cell.
/// Possible values: "Unknown", "Null", "Numeric", "DateTime", "String", "Bool", "Error".
/// Helps the agent determine how to interpret cell data before reading it.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="cellReference">Cell reference in A1 notation (e.g. "A1").</param>
/// <returns>The value type name, or null if the cell is not found.</returns>
public string? GetCellType(string sheetName, string cellReference)
{
var ws = FindSheet(sheetName);
if (ws == null || !TryParseCellRef(cellReference).Ok) return null;
var cell = ws.Cells[cellReference];
if (cell == null) return null;
return cell.Type switch
{
CellValueType.IsNull => "Null",
CellValueType.IsNumeric => "Numeric",
CellValueType.IsDateTime => "DateTime",
CellValueType.IsString => "String",
CellValueType.IsBool => "Bool",
CellValueType.IsError => "Error",
_ => "Unknown",
};
}
// ──────────────────────────────────────────────
// Bulk operations
// ──────────────────────────────────────────────
/// <summary>
/// Reads a rectangular range as a 2D string array.
/// Empty cells are returned as empty strings.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="startCell">Top-left cell (e.g. "A1").</param>
/// <param name="endCell">Bottom-right cell (e.g. "C10").</param>
/// <param name="detailed">When true, returns an enriched JSON object instead of the raw 2D
/// array: the sheet name and the exact A1 range (position on the page), plus SPARSE
/// "formulas"/"types"/"formats" objects that list ONLY the cells carrying that information
/// (cells not listed in "types" are numeric) — so the agent gets a verifiable, compact
/// picture of the area as feedback/memory for its work.</param>
/// <returns>2D string array [row][col] (or the enriched object with detailed=true),
/// or null if the sheet is not found.</returns>
public object? GetRange(string sheetName, string startCell, string endCell, bool detailed = false)
{
var ws = FindSheet(sheetName);
if (ws == null) return null;
var a = TryParseCellRef(startCell);
var b = TryParseCellRef(endCell);
if (!a.Ok || !b.Ok) return null;
var (startRow, startCol) = (Math.Min(a.Row, b.Row), Math.Min(a.Col, b.Col));
var (endRow, endCol) = (Math.Max(a.Row, b.Row), Math.Max(a.Col, b.Col));
if (detailed)
return DescribeArea(ws, startRow, startCol, endRow, endCol);
int rows = endRow - startRow + 1;
int cols = endCol - startCol + 1;
var result = new string[rows][];
for (int r = 0; r < rows; r++)
{
result[r] = new string[cols];
for (int c = 0; c < cols; c++)
{
var cell = ws.Cells[startRow + r, startCol + c];
result[r][c] = cell?.DisplayStringValue ?? string.Empty;
}
}
return result;
}
/// <summary>Builds the compact, SPARSE JSON representation of a rectangular area: sheet
/// name + exact A1 range (position on the page) + dimensions + display values; the
/// "formulas"/"types"/"formats" objects include ONLY the cells that carry that information
/// (empty sections are omitted entirely — no null/empty fields — to keep the token cost
/// low). Cells not listed in "types" are numeric. Used by GetRange(detailed=true) and by
/// every write method as the feedback/receipt of what was modified.</summary>
private Dictionary<string, object?> DescribeArea(Worksheet ws, int startRow, int startCol, int endRow, int endCol)
{
var values = new List<object[]>();
var formulas = new Dictionary<string, object>();
var types = new Dictionary<string, object>();
var formats = new Dictionary<string, object>();
for (int r = startRow; r <= endRow; r++)
{
var row = new List<object>();
for (int c = startCol; c <= endCol; c++)
{
var cell = ws.Cells[r, c];
row.Add(cell?.DisplayStringValue ?? "");
if (cell == null) continue;
var refName = CellRefFromIdx(r, c);
if (!string.IsNullOrEmpty(cell.Formula))
formulas[refName] = cell.Formula.StartsWith('=') ? cell.Formula : "=" + cell.Formula;
else if (cell.Type is CellValueType.IsString or CellValueType.IsDateTime
or CellValueType.IsBool or CellValueType.IsError)
types[refName] = cell.Type switch
{
CellValueType.IsString => "text",
CellValueType.IsDateTime => "date",
CellValueType.IsBool => "bool",
_ => "error",
};
var custom = cell.GetStyle().Custom;
if (!string.IsNullOrEmpty(custom))
formats[refName] = custom;
}
values.Add(row.ToArray());
}
var result = new Dictionary<string, object?>
{
["sheet"] = ws.Name,
["range"] = $"{CellRefFromIdx(startRow, startCol)}:{CellRefFromIdx(endRow, endCol)}",
["rows"] = endRow - startRow + 1,
["columns"] = endCol - startCol + 1,
["values"] = values,
};
if (formulas.Count > 0) result["formulas"] = formulas;
if (types.Count > 0) result["types"] = types;
if (formats.Count > 0) result["formats"] = formats;
return result;
}
/// <summary>
/// Writes a 2D string array starting at the specified cell.
/// Auto-detects number, boolean, date, and string values.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="startCell">Top-left cell (e.g. "A1").</param>
/// <param name="values">2D array of STRINGS [row][col]; pass numbers as strings (e.g. "14500") — the tool auto-detects and stores them as numbers. Rows may have different lengths.</param>
/// <returns>The area receipt for the written block (sheet, exact A1 range, dimensions,
/// values, formulas/types/formats when present — feedback for the agent to verify its own
/// work), or "Error: …" when the sheet/cell reference is invalid or the block is too
/// large (nothing is written on error).</returns>
public object SetRange(string sheetName, string startCell, string[][] values)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
if (values == null || values.Length == 0) return "Error: no rows to write";
var p = TryParseCellRef(startCell);
if (!p.Ok) return $"Error: {p.Error}";
// Guard the whole block BEFORE writing a single cell: a partial write followed by a
// later failure would leave the workbook half-modified with no way to report it.
// Null rows are treated as empty rows — an irregular block must never throw.
int maxCols = values.Max(r => r?.Length ?? 0);
long area = values.Sum(r => (long)(r?.Length ?? 0));
if (maxCols == 0) return "Error: no values to write";
if (area > MaxCellArea) return $"Error: the values block is too large ({area} cells, max {MaxCellArea})";
if (p.Row + values.Length > 1_048_576) return "Error: the values block extends past the last row (1048576)";
var (startRow, startCol) = (p.Row, p.Col);
for (int c = 0; c < maxCols; c++)
MarkColumnTouched(ws.Name, startCol + c);
for (int r = 0; r < values.Length; r++)
{
if (values[r] == null) continue;
for (int c = 0; c < values[r].Length; c++)
{
var cell = ws.Cells[startRow + r, startCol + c];
if (cell != null)
SetCellValueAuto(cell, values[r][c]);
}
}
_dirty = true;
Log.LogStep($"SpreadsheetTool.SetRange: '{sheetName}'!{startCell} ({values.Length} rows)");
return DescribeArea(ws, startRow, startCol, startRow + values.Length - 1, startCol + maxCols - 1);
}
/// <summary>
/// Appends rows after the last used row on the worksheet.
/// The last used row is detected across ALL columns (values AND formulas), so rows are
/// never appended on top of existing content.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="rows">Array of rows to append.</param>
/// <returns>The area receipt for the appended block (sheet, exact A1 range, dimensions,
/// values — feedback for the agent to verify its own work), or "Error: …" when the sheet
/// is missing or the block is too large (nothing is written on error).</returns>
public object AppendRows(string sheetName, string[][] rows)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
if (rows == null || rows.Length == 0 || rows[0].Length == 0) return "Error: no rows to append";
// Append AFTER the true last used row: the max over ALL columns of a value-OR-formula
// scan. A display-only scan on column A would (a) ignore data sitting in other columns
// and (b) stop at the first formula cell (formulas display as empty without
// recalculation) — both would append on top of existing content and overwrite it.
int startRow = FindLastUsedRow(ws) + 1;
int maxCols = rows.Max(r => r?.Length ?? 0);
long area = rows.Sum(r => (long)(r?.Length ?? 0));
if (maxCols == 0) return "Error: no values to append";
if (area > MaxCellArea) return $"Error: the rows block is too large ({area} cells, max {MaxCellArea})";
if (startRow + rows.Length > 1_048_576) return "Error: the rows block extends past the last row (1048576)";
for (int c = 0; c < maxCols; c++)
MarkColumnTouched(ws.Name, c);
for (int r = 0; r < rows.Length; r++)
{
if (rows[r] == null) continue;
for (int c = 0; c < rows[r].Length; c++)
{
var cell = ws.Cells[startRow + r, c];
if (cell != null)
SetCellValueAuto(cell, rows[r][c]);
}
}
_dirty = true;
Log.LogStep($"SpreadsheetTool.AppendRows: '{sheetName}' ({rows.Length} rows from row {startRow})");
return DescribeArea(ws, startRow, 0, startRow + rows.Length - 1, maxCols - 1);
}
// ──────────────────────────────────────────────
// Merge
// ──────────────────────────────────────────────
/// <summary>
/// Merges a rectangular range of cells into one cell.
/// Only the upper-left cell value is preserved.
/// </summary>
/// <param name="sheetName">Worksheet name (case-sensitive, from GetSheetNames()).</param>
/// <param name="range">Range in A1 notation (e.g. "A1:C3").</param>
/// <returns>"true", or "Error: …" when the sheet or the range is invalid.</returns>
public string MergeCells(string sheetName, string range)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
var p = TryParseRange(range);
if (!p.Ok) return $"Error: {p.Error}";
ws.Cells.Merge(p.R1, p.C1, p.R2 - p.R1 + 1, p.C2 - p.C1 + 1);
_dirty = true;
Log.LogStep($"SpreadsheetTool.MergeCells: '{sheetName}'!{range}");
return "true";
}
// ──────────────────────────────────────────────
// Style — all-in-one
// ──────────────────────────────────────────────
/// <summary>
/// Applies multiple style properties in a single call — the ONLY style method the agent
/// needs (font, fill, alignment, wrap, number format and borders).
/// Only non-null/non-default parameters are applied.
/// Colors: "#RRGGBB". Pass fillColorHex "none" to remove the fill.
/// Horizontal: "Left","Center","Right". Vertical: "Top","Center","Bottom".
/// Border styles: "Thin","Medium","Thick","Dotted","Dashed","Double","Hair".
/// Border sides: "All","Outline","Inside","Top","Bottom","Left","Right".
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="cellOrRange">Cell or range (e.g. "A1" or "A1:C10").</param>
/// <param name="fontName">Font family.</param>
/// <param name="fontSize">Font size in points.</param>
/// <param name="bold">True = bold.</param>
/// <param name="italic">True = italic.</param>
/// <param name="fontColorHex">Font color "#RRGGBB".</param>
/// <param name="fillColorHex">Background color "#RRGGBB", or "none" to remove the fill.</param>
/// <param name="horizontalAlignment">Horizontal: "Left","Center","Right".</param>
/// <param name="verticalAlignment">Vertical: "Top","Center","Bottom".</param>
/// <param name="wrapText">True = wrap text.</param>
/// <param name="numberFormat">Custom number format (e.g. "#,##0.00"). Pass it as a plain
/// string WITHOUT surrounding quotes — a quoted string is a literal in Excel format syntax.</param>
/// <param name="borderStyle">Border line style (e.g. "Thin"). Only applied when set.</param>
/// <param name="borderSide">Which sides to border (default "All").</param>
/// <param name="borderColorHex">Border color "#RRGGBB" (default black).</param>
/// <returns>The style receipt — sheet, styled range and the list of parameters actually
/// applied (feedback for the agent to verify its own work), or "Error: …" on invalid input.</returns>
public object ApplyStyle(string sheetName, string cellOrRange,
string? fontName = null, double fontSize = 0,
bool? bold = null, bool? italic = null,
string? fontColorHex = null, string? fillColorHex = null,
string? horizontalAlignment = null, string? verticalAlignment = null,
bool? wrapText = null, string? numberFormat = null,
string? borderStyle = null, string? borderSide = null, string? borderColorHex = null)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
var guard = ValidateCellOrRange(cellOrRange);
if (guard != null) return $"Error: {guard}";
var p = TryParseRange(cellOrRange);
if (!p.Ok) return $"Error: {p.Error}";
var (r1, c1, r2, c2) = (p.R1, p.C1, p.R2, p.C2);
for (int c = c1; c <= c2; c++)
MarkColumnTouched(ws.Name, c);
// Border parameters are resolved once, outside the cell loop. "Inside" borders only
// the edges BETWEEN cells (outer perimeter excluded); "Outline" borders only the
// outer perimeter; a single-cell range has no inner borders.
BorderStyleType? border = string.IsNullOrEmpty(borderStyle) ? null : ParseBorderStyle(borderStyle);
bool inside = borderSide?.Equals("Inside", StringComparison.OrdinalIgnoreCase) == true;
bool outline = borderSide?.Equals("Outline", StringComparison.OrdinalIgnoreCase) == true;
var sides = inside || outline
? new[] { "Top", "Bottom", "Left", "Right" }
: ParseBorderSides(borderSide ?? "All");
var borderColor = !string.IsNullOrEmpty(borderColorHex)
? ParseColor(borderColorHex)
: Color.FromArgb(255, 0, 0, 0);
for (int r = r1; r <= r2; r++)
{
for (int c = c1; c <= c2; c++)
{
var cell = ws.Cells[r, c];
if (cell == null) continue;
var style = cell.GetStyle();
if (!string.IsNullOrEmpty(fontName)) style.Font.Name = fontName;
if (fontSize > 0) style.Font.Size = fontSize;
if (bold.HasValue) style.Font.IsBold = bold.Value;
if (italic.HasValue) style.Font.IsItalic = italic.Value;
if (!string.IsNullOrEmpty(fontColorHex)) style.Font.Color = ParseColor(fontColorHex);
if (!string.IsNullOrEmpty(fillColorHex))
{
if (fillColorHex.Equals("none", StringComparison.OrdinalIgnoreCase))
style.Pattern = FillPattern.None;
else
{
style.Pattern = FillPattern.Solid;
style.ForegroundColor = ParseColor(fillColorHex);
}
}
if (!string.IsNullOrEmpty(horizontalAlignment))
style.HorizontalAlignment = ParseHorizontalAlignment(horizontalAlignment);
if (!string.IsNullOrEmpty(verticalAlignment))
style.VerticalAlignment = ParseVerticalAlignment(verticalAlignment);
if (wrapText.HasValue)
style.WrapText = wrapText.Value;
if (!string.IsNullOrEmpty(numberFormat))
style.Custom = NormalizeNumberFormat(numberFormat);
if (border.HasValue)
{
var borders = style.Borders;
foreach (var side in sides)
{
if (inside && !IsInnerEdge(side, r, c, r1, c1, r2, c2)) continue;
if (outline && !IsOuterEdge(side, r, c, r1, c1, r2, c2)) continue;
switch (side)
{
case "Top":
borders.Top.LineStyle = border.Value;
borders.Top.Color = borderColor;
break;
case "Bottom":
borders.Bottom.LineStyle = border.Value;
borders.Bottom.Color = borderColor;
break;
case "Left":
borders.Left.LineStyle = border.Value;
borders.Left.Color = borderColor;
break;
case "Right":
borders.Right.LineStyle = border.Value;
borders.Right.Color = borderColor;
break;
}
}
}
cell.SetStyle(style);
}
}
var applied = new List<object>();
if (!string.IsNullOrEmpty(fontName)) applied.Add("font '" + fontName + "'");
if (fontSize > 0) applied.Add("fontSize " + fontSize);
if (bold.HasValue) applied.Add("bold=" + bold.Value.ToString().ToLowerInvariant());
if (italic.HasValue) applied.Add("italic=" + italic.Value.ToString().ToLowerInvariant());
if (!string.IsNullOrEmpty(fontColorHex)) applied.Add("fontColor " + fontColorHex);
if (!string.IsNullOrEmpty(fillColorHex))
applied.Add(fillColorHex.Equals("none", StringComparison.OrdinalIgnoreCase) ? "fill none" : "fill " + fillColorHex);
if (!string.IsNullOrEmpty(horizontalAlignment)) applied.Add("hAlign " + horizontalAlignment);
if (!string.IsNullOrEmpty(verticalAlignment)) applied.Add("vAlign " + verticalAlignment);
if (wrapText.HasValue) applied.Add("wrapText=" + wrapText.Value.ToString().ToLowerInvariant());
if (!string.IsNullOrEmpty(numberFormat)) applied.Add("numberFormat '" + NormalizeNumberFormat(numberFormat) + "'");
if (border.HasValue) applied.Add("border " + borderStyle + (borderSide != null && borderSide != "All" ? " (" + borderSide + ")" : ""));
Log.LogStep($"SpreadsheetTool.ApplyStyle: '{sheetName}'!{cellOrRange}");
_dirty = true;
return new Dictionary<string, object?>
{
["sheet"] = ws.Name,
["range"] = $"{CellRefFromIdx(r1, c1)}:{CellRefFromIdx(r2, c2)}",
["applied"] = applied,
};
}
/// <summary>True when the given side of cell (r,c) is an edge INSIDE the range (both
/// neighbors in range) — used for "Inside" borders, which skip the outer perimeter.</summary>
private static bool IsInnerEdge(string side, int r, int c, int r1, int c1, int r2, int c2) =>
(side == "Top" && r > r1) || (side == "Bottom" && r < r2)
|| (side == "Left" && c > c1) || (side == "Right" && c < c2);
/// <summary>True when the given side of cell (r,c) lies on the outer perimeter of the
/// range — used for "Outline" borders.</summary>
private static bool IsOuterEdge(string side, int r, int c, int r1, int c1, int r2, int c2) =>
(side == "Top" && r == r1) || (side == "Bottom" && r == r2)
|| (side == "Left" && c == c1) || (side == "Right" && c == c2);
// ──────────────────────────────────────────────
// Style — header row shortcut
// ──────────────────────────────────────────────
/// <summary>
/// Applies a bold white-on-blue header style to the first row.
/// Detects the used column count from row 0.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <returns>The style receipt — sheet, the formatted header range and the list of applied
/// parameters (feedback for the agent to verify its own work), or "Error: …" when the
/// sheet is missing or the header row is empty.</returns>
public object FormatHeaderRow(string sheetName)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
int maxCol = 0;
while (true)
{
var cell = ws.Cells[0, maxCol];
if (cell == null || string.IsNullOrEmpty(cell.DisplayStringValue))
break;
maxCol++;
}
if (maxCol == 0) return "Error: the header row is empty (no cells to format)";
for (int c = 0; c < maxCol; c++)
{
var cell = ws.Cells[0, c];
if (cell == null) continue;
MarkColumnTouched(ws.Name, c);
var style = cell.GetStyle();
style.Font.IsBold = true;
style.Font.Color = Color.FromArgb(255, 255, 255, 255);
style.Pattern = FillPattern.Solid;
style.ForegroundColor = Color.FromArgb(255, 34, 120, 212);
cell.SetStyle(style);
}
Log.LogStep($"SpreadsheetTool.FormatHeaderRow: '{sheetName}' ({maxCol} columns)");
_dirty = true;
return new Dictionary<string, object?>
{
["sheet"] = ws.Name,
["range"] = $"{CellRefFromIdx(0, 0)}:{CellRefFromIdx(0, maxCol - 1)}",
["applied"] = new object[] { "bold", "fontColor white", "fill #2278D4" },
};
}
// ──────────────────────────────────────────────
// Row & column
// ──────────────────────────────────────────────
/// <summary>
/// Sets the height of a specific row (0-based index).
/// Height is in points (default row height is ~15 points).
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="rowIndex">0-based row index.</param>
/// <param name="heightInPoints">Row height in points. Use -1 to reset to default.</param>
/// <returns>"true", or "Error: …" if the row height was set.</returns>
public string SetRowHeight(string sheetName, int rowIndex, double heightInPoints)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
if (rowIndex < 0 || rowIndex > 1_048_575) return $"Error: row index {rowIndex} out of range (0..1048575)";
ws.Cells.Rows[rowIndex].Height = heightInPoints >= 0 ? heightInPoints : null;
Log.LogStep($"SpreadsheetTool.SetRowHeight: '{sheetName}' row={rowIndex} height={heightInPoints}");
_dirty = true;
return "true";
}
/// <summary>
/// Hides a specific row (0-based index).
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="rowIndex">0-based row index.</param>
/// <returns>"true", or "Error: …" if the row was hidden.</returns>
public string HideRow(string sheetName, int rowIndex)
{
var ws = FindSheet(sheetName);
if (ws == null) return $"Error: worksheet '{sheetName}' not found";
if (rowIndex < 0 || rowIndex > 1_048_575) return $"Error: row index {rowIndex} out of range (0..1048575)";
ws.Cells.Rows[rowIndex].IsHidden = true;
Log.LogStep($"SpreadsheetTool.HideRow: '{sheetName}' row={rowIndex}");
_dirty = true;
return "true";
}
/// <summary>
/// Unhides a previously hidden row.
/// </summary>
/// <param name="sheetName">Worksheet name (from GetSheetNames()).</param>
/// <param name="rowIndex">0-based row index.</param>
/// <returns>"true", or "Error: …" if the row was unhidden.</returns>
public string UnhideRow(string sheetName, int rowIndex)
{
var ws = FindSheet(sheetName);