Remove DataLinks in an Excel Workbook Programmatically

Remove DataLinks in an Excel Workbook Programmatically

This tip shows you how to automate the process of removing DataLinks in Excel using C#. A DataLink is a link stored in one Workbook that retrieves data from another Workbook. For example, suppose you have a chart in one Workbook that gets its data from another Workbook. That’s fine, as long as both Workbooks are available. However, if you want to send only the Workbook containing the chart, you need to remove the dependency on the Workbook containing the data.

Excel provides an Edit Links option to break the DataLinks manually. When you do so, Excel copies the current data values to populate the chart (or any other Excel object that uses DataLink data) from the source Workbook. Of course, you can break the links programmatically as well.

To get started, reference Microsoft’s Excel Interop Library in a .NET project. The Interop Library lets you access Excel Workbooks. The following function breaks the links in the Workbook you pass in as a parameter:

/// <summary>/// Breaks the DataLinks in a WorkBook/// /// private void BreakDataLinks(Excel._Workbook wb){            if (DialogResult.Yes ==       MessageBox.Show(this,      "Do you want to break the links to Data Sources ?",       "Links", MessageBoxButtons.YesNo))   {      Array links = (Array)wb.LinkSources(         Excel.XlLink.xlExcelLinks);      if (links != null)      {         for (int i = 1; i <= links.Length; i++)         {            wb.BreakLink((string)links.GetValue(i),            Excel.XlLinkType.xlLinkTypeExcelLinks);         }      }   }}

You also should suppress the Excel confirmation dialog that pops up when you break a DataLink. The following function suppresses the confirmation dialog:

oXL.DisplayAlerts   = false;oXL.AskToUpdateLinks = false; 

In the preceding code, oXL is the Excel Application Object defined as follows:

//Excel Application ObjectExcel.Application oXL;oXL = new Excel.Application();
See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist