private static void UpdateHyperlinkReferences(WorksheetPart worksheetPart, uint rowIndex, bool isDeletedRow) { Hyperlinks hyperlinks = worksheetPart.Worksheet.Elements <Hyperlinks>().FirstOrDefault(); if (hyperlinks == null) { return; } foreach (Hyperlink hyperlink in hyperlinks.Elements <Hyperlink>()) { var hyperlinkRowIndexMatch = Regex.Match(hyperlink.Reference.Value, "[0-9]+"); uint hyperlinkRowIndex; if (!hyperlinkRowIndexMatch.Success || !uint.TryParse(hyperlinkRowIndexMatch.Value, out hyperlinkRowIndex) || hyperlinkRowIndex < rowIndex) { continue; } // if being deleted, hyperlink needs to be removed or moved up if (isDeletedRow) { // if hyperlink is on the row being removed, remove it if (hyperlinkRowIndex == rowIndex) { hyperlink.Remove(); } // else hyperlink needs to be moved up a row else { hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex - 1).ToString()); } } // else row is being inserted, move hyperlink down else { hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex + 1).ToString()); } } // Remove the hyperlinks collection if none remain if (!hyperlinks.Elements <Hyperlink>().Any()) { hyperlinks.Remove(); } }
/// <summary> /// Updates all hyperlinks in the worksheet when a row is inserted or deleted. /// </summary> /// <param name="worksheetPart">Worksheet Part</param> /// <param name="rowIndex">Row Index being inserted or deleted</param> /// <param name="isDeletedRow">True if row was deleted, otherwise false</param> private void UpdateHyperlinkReferences(uint rowIndex, bool isDeletedRow) { Hyperlinks hyperlinks = this.WorksheetPart.Worksheet.Elements <Hyperlinks>().FirstOrDefault(); if (hyperlinks != null) { Match hyperlinkRowIndexMatch; uint hyperlinkRowIndex; foreach (Hyperlink hyperlink in hyperlinks.Elements <Hyperlink>()) { hyperlinkRowIndexMatch = Regex.Match(hyperlink.Reference.Value, "[0-9]+"); if (hyperlinkRowIndexMatch.Success && UInt32.TryParse(hyperlinkRowIndexMatch.Value, out hyperlinkRowIndex) && hyperlinkRowIndex >= rowIndex) { // if being deleted, hyperlink needs to be removed or moved up if (isDeletedRow) { // if hyperlink is on the row being removed, remove it if (hyperlinkRowIndex == rowIndex) { hyperlink.Remove(); } // else hyperlink needs to be moved up a row else { hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex - 1).ToString()); } } // else row is being inserted, move hyperlink down else { hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex + 1).ToString()); } } } // Remove the hyperlinks collection if none remain if (hyperlinks.Elements <Hyperlink>().Count() == 0) { hyperlinks.Remove(); } } }