Created
June 10, 2020 18:46
-
-
Save derrickturk/c9c33a8c6f45dfd12bda4f57219dd522 to your computer and use it in GitHub Desktop.
Excel regex link rewriter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Text.RegularExpressions; | |
using Excel = Microsoft.Office.Interop.Excel; | |
class Guarded<T> : IDisposable { | |
public Guarded(T val, Action<T> onDispose) | |
{ | |
this.val = val; | |
this.onDispose = onDispose; | |
} | |
public T Value { | |
get { return val; } | |
} | |
public void Dispose() | |
{ | |
onDispose(val); | |
} | |
private T val; | |
private Action<T> onDispose; | |
} | |
static class UpLink { | |
public static void rewriteLinks(Excel.Worksheet ws, | |
string pat, string replace) | |
{ | |
foreach (Excel.Hyperlink h in ws.Hyperlinks) { | |
h.Address = Regex.Replace(h.Address, pat, replace); | |
} | |
} | |
public static void Main(string[] args) | |
{ | |
if (args.Length != 3) | |
{ | |
Console.Error.WriteLine( | |
"Usage: uplink workbook-path find-pattern replace-pattern"); | |
return; | |
} | |
var wbPath = Path.GetFullPath(args[0]); | |
using (var xl = new Guarded<Excel.Application>( | |
new Excel.Application(), | |
xl => xl.Quit())) { | |
using (var wb = new Guarded<Excel.Workbook>( | |
xl.Value.Workbooks.Open(wbPath), | |
wb => wb.Close(false))) { | |
foreach (Excel.Worksheet ws in wb.Value.Worksheets) { | |
rewriteLinks(ws, args[1], args[2]); | |
} | |
wb.Value.Save(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment