NanoXLSX.Compatibility 3.2.0
Loading...
Searching...
No Matches
ExternalLinkWorksheetInlineWriter.cs
1/*
2 * NanoXLSX is a small .NET library to generate and read XLSX (Microsoft Excel 2007 or newer) files in an easy and native way
3 * Copyright Raphael Stoeckli © 2026
4 * This library is licensed under the MIT License.
5 * You find a copy of the license in project folder or on: http://opensource.org/licenses/MIT
6 */
7
9using NanoXLSX.Interfaces.Writer;
10using NanoXLSX.Registry;
11using NanoXLSX.Registry.Attributes;
12using NanoXLSX.Utils.Xml;
13using System.Collections.Generic;
14using System.Linq;
15
17{
18 [NanoXlsxQueuePlugIn(PlugInUUID = "EXTERNAL_LINK_INLINE_WORKSHEET_WRITER", QueueUUID = PlugInUUID.WorksheetInlineWriter, PlugInOrder = 100000)]
19 internal class ExternalLinkWorksheetInlineWriter : IPluginInlineWriter
20 {
21 #region privateFields
22 private Worksheet currentWorksheet;
23 #endregion
24 #region properties
28 public Workbook Workbook { get; set; }
32 public IWriteContext WriteContext { get; set; } // NoOp
36 public XmlElement RootElement { get; set; }
40 public XmlElement XmlElement { get; } // NoOp
41 #endregion
42 #region methods
49 public void Init(ref XmlElement rootElement, Workbook workbook, int? index = null)
50 {
51 Workbook = workbook;
52 RootElement = rootElement;
53 // Note: The worksheet writer or will pass the 1-based sheetID, not the 0-based index
54 currentWorksheet = Workbook.Worksheets.First(w => w.SheetID == index); // This should never fail
55 }
56
60 public void Execute()
61 {
62 if (!currentWorksheet.Features.ContainsExternalLinks)
63 {
64 return; // Nothing to do
65 }
66 ReplaceFormulas();
67 // TODO add further worksheet-related processing, if external links are somewhere else too
68 }
69
73 private void ReplaceFormulas()
74 {
75 Dictionary<int, Dictionary<string, ExternalLinkResolution>> externalLinks =
76 Workbook.AuxiliaryData.GetData<Dictionary<int, Dictionary<string, ExternalLinkResolution>>>(PlugInUUID.CompatibilityInlineProcessor, CompatibilityConstants.EXTERNAL_LINK_RESOLVED_FORMULAS_ENTITY);
77 if (externalLinks == null || externalLinks.Count == 0 || !externalLinks.TryGetValue(currentWorksheet.SheetID, out Dictionary<string, ExternalLinkResolution> externalLink))
78 {
79 return; // No formulas or external links to process
80 }
81 foreach (KeyValuePair<string, ExternalLinkResolution> extLinkFormula in externalLink)
82 {
83 IEnumerable<XmlElement> cells = RootElement.FindChildElementsByNameAndAttribute("c", "r", extLinkFormula.Key);
84 // This should never be ambiguous or non-existing
85 XmlElement cell = cells.FirstOrDefault();
86 if (cell != null)
87 {
88 IEnumerable<XmlElement> formulas = cell.FindChildElementsByName("f");
89 // This should never be ambiguous or non-existing
90 XmlElement formula = formulas.FirstOrDefault();
91 if (formula != null)
92 {
93 formula.InnerValue = extLinkFormula.Value.Expression;
94 }
95 }
96 }
97 }
98 #endregion
99
100 }
101}