Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: .NET
Expertise: Intermediate
Jul 27, 2009

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 Object
Excel.Application oXL;
oXL = new Excel.Application();
Srinath MS
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap