How to delete hyperlinks from a worksheet without affecting the cell styles using C#?
You can remove hyperlinks from an Excel worksheet without altering the cell formatting using HyperLinks property of the IWorksheet interface. Below are the code examples in C# (cross-platform and Windows-specific) and VB.NET to demonstrate how to do this.
using (ExcelEngine excelEngine = new ExcelEngine())
{
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Xlsx;
FileStream inputStream = new FileStream("Data/InputTemplate.xlsx", FileMode.Open, FileAccess.Read);
IWorkbook workbook = application.Workbooks.Open(inputStream);
IWorksheet worksheet = workbook.Worksheets[0];
// Remove first hyperlink without affecting cell styles
HyperLinksCollection hyperlink = worksheet.HyperLinks as HyperLinksCollection;
hyperlink.Remove(hyperlink[0] as HyperLinkImpl);
FileStream outputStream = new FileStream("Output/Output.xlsx", FileMode.Create, FileAccess.Write);
workbook.SaveAs(outputStream);
workbook.Close();
excelEngine.Dispose();
}
using (ExcelEngine engine = new ExcelEngine())
{
IApplication application = engine.Excel;
IWorkbook workbook = application.Workbooks.Open("InputTemplate.xlsx");
IWorksheet worksheet = workbook.Worksheets[0];
// Remove first hyperlink without affecting cell styles
HyperLinksCollection hyperlink = worksheet.HyperLinks as HyperLinksCollection;
hyperlink.Remove(hyperlink[0] as HyperLinkImpl);
workbook.SaveAs("Output.xlsx");
workbook.Close();
}
Using engine As New ExcelEngine()
Dim application As IApplication = engine.Excel
Dim workbook As IWorkbook = application.Workbooks.Open("InputTemplate.xlsx")
Dim worksheet As IWorksheet = workbook.Worksheets(0)
' Remove first hyperlink without affecting cell style
Dim hyperlink As HyperLinksCollection = TryCast(worksheet.HyperLinks, HyperLinksCollection)
hyperlink.Remove(TryCast(hyperlink(0), HyperLinkImpl))
Using outputStream As New FileStream("Output.xlsx", FileMode.Create, FileAccess.Write)
workbook.SaveAs(outputStream)
End Using
workbook.Close()
End Using
A complete working example to delete hyperlinks from an Excel worksheet without altering cell styles is available on this GitHub page.