2010-05-25 80 views
0

我似乎无法找到关于如何使用Open XML SDK 2.0向Excel 2007中的单元添加超链接的任何文档或代码示例。我正在使用下面的代码,但是有一个步骤我失踪了?使用Open XML SDK 2.0在Excel 2007中添加超链接使用Open XML SDK 2.0

WorksheetPart workSheetPart = ExcelUtilities.GetWorkSheetPart(mWorkBookPart, "Program"); 

workSheetPart.AddHyperlinkRelationship(new Uri("http://www.google.com", UriKind.Absolute), true); 

workSheetPart.Worksheet.Save(); 

mWorkBookPart.Workbook.Save(); 

后来,当我尝试打开Excel文档它说,该文件被损坏,因为关系ID超链接无法找到。你如何设置或创建该关系ID?

回答

2

我能够使用System.IO.Packaging代码超链接添加到单元格:

private void HyperlinkCreate(PackagePart part, XmlNamespaceManager nsm, XmlNode _cellElement, string CellAddress) 
{ 
     Uri _hyperlink = new Uri("http://www.yahoo.com"); 
     XmlNode linkParent = _cellElement.OwnerDocument.SelectSingleNode("//d:hyperlinks", nsm); 
     if (linkParent == null) 
     { 
      // create the hyperlinks node 
      linkParent = _cellElement.OwnerDocument.CreateElement("hyperlinks", @"http://schemas.openxmlformats.org/spreadsheetml/2006/main"); 
      XmlNode prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:conditionalFormatting", nsm); 
      if (prevNode == null) 
      { 
       prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:mergeCells", nsm); 
       if (prevNode == null) 
       { 
        prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:sheetData", nsm); 
       } 
      } 
      _cellElement.OwnerDocument.DocumentElement.InsertAfter(linkParent, prevNode); 
     } 
     string searchString = string.Format("./d:hyperlink[@ref = '{0}']", CellAddress); 
     XmlElement linkNode = (XmlElement)linkParent.SelectSingleNode(searchString, nsm); 
     XmlAttribute attr; 
     if (linkNode == null) 
     { 
      linkNode = _cellElement.OwnerDocument.CreateElement("hyperlink", @"http://schemas.openxmlformats.org/spreadsheetml/2006/main"); 
      // now add cell address attribute 
      linkNode.SetAttribute("ref", CellAddress); 
      linkParent.AppendChild(linkNode); 
     } 

     attr = (XmlAttribute)linkNode.Attributes.GetNamedItem("id", @"http://schemas.openxmlformats.org/officeDocument/2006/relationships"); 
     if (attr == null) 
     { 
      attr = _cellElement.OwnerDocument.CreateAttribute("r", "id", @"http://schemas.openxmlformats.org/officeDocument/2006/relationships"); 
      linkNode.Attributes.Append(attr); 
     }      

     PackageRelationship relationship = null; 
     string relID = attr.Value; 
     if (relID == "") 
      relationship = part.CreateRelationship(_hyperlink, TargetMode.External, @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"); 
     else 
     { 
      relationship = part.GetRelationship(relID); 
      if (relationship.TargetUri != _hyperlink) 
       relationship = part.CreateRelationship(_hyperlink, TargetMode.External, @"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"); 
     } 
     attr.Value = relationship.Id; 
} 

我然后使用Open XML SDK 2.0编译代码并没有关系没有工作。看来AddHyperlinkRelationship方法实际上并没有将该关系添加到.rels文件中。我不知道为什么,但它肯定对我来说似乎是一个错误。

private void HyperlinkCreate(PackagePart part, XmlNamespaceManager nsm, XmlNode _cellElement, string CellAddress) 
    { 

WorksheetPart workSheetPart = ExcelUtilities.GetWorkSheetPart(mWorkBookPart, "Program"); 
      Uri hyperlinkUri = new Uri("http://www.yahoo.com", UriKind.Absolute); 

      Hyperlinks hyperlinks = workSheetPart.Worksheet.Descendants<Hyperlinks>().FirstOrDefault(); 

      // Check to see if the <x:hyperlinks> element exists; if not figure out 
      // where to insert it depending on which elements are present in the Worksheet 
      if (hyperlinks == null) 
      { 
       // Create the hyperlinks node 
       hyperlinks = new Hyperlinks(); 

       OpenXmlCompositeElement prevElement = workSheetPart.Worksheet.Descendants<ConditionalFormatting>().FirstOrDefault(); 
       if (prevElement == null) 
       { 
        prevElement = workSheetPart.Worksheet.Descendants<MergeCells>().FirstOrDefault(); 
        if (prevElement == null) 
        { 
         // No FirstOrDefault needed since a Worksheet requires SheetData or the excel doc will be corrupt 
         prevElement = workSheetPart.Worksheet.Descendants<SheetData>().First(); 
        } 
       } 
       workSheetPart.Worksheet.InsertAfter(hyperlinks, prevElement); 
      } 
      Hyperlink hyperlink = hyperlinks.Descendants<Hyperlink>().Where(r => r.Reference.Equals(CellAddress)).FirstOrDefault(); 
      if (hyperlink == null) 
      { 
       hyperlink = new Hyperlink() { Reference = CellAddress, Id = string.Empty }; 

      } 

      HyperlinkRelationship hyperlinkRelationship = null; 
      string relId = hyperlink.Id; 
      if (relId.Equals(string.Empty)) 
      { 
       hyperlinkRelationship = workSheetPart.AddHyperlinkRelationship(hyperlinkUri, true); 
      } 
      else 
      { 
       hyperlinkRelationship = workSheetPart.GetReferenceRelationship(relId) as HyperlinkRelationship; 
       if (!hyperlinkRelationship.Uri.Equals(hyperlinkUri)) 
       { 
        hyperlinkRelationship = workSheetPart.AddHyperlinkRelationship(hyperlinkUri, true); 
       } 
      } 
      hyperlink.Id = hyperlinkRelationship.Id; 
      hyperlinks.AppendChild<Hyperlink>(hyperlink); 
      workSheetPart.Worksheet.Save();  
     } 
1

您应该将其添加到接受超链接的对象(例如单元格)而不是工作表。像这样的东西应该为你工作:

using DocumentFormat.OpenXml.Spreadsheet; 
using DocumentFormat.OpenXml; 

namespace GeneratedCode 
{ 
    public class GeneratedClass 
    { 
     // Creates an Worksheet instance and adds its children. 
     public Worksheet GenerateWorksheet() 
     { 
      Worksheet worksheet1 = new Worksheet(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x14ac" } }; 
      worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships"); 
      worksheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006"); 
      worksheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"); 
      SheetDimension sheetDimension1 = new SheetDimension(){ Reference = "A1" }; 

      SheetViews sheetViews1 = new SheetViews(); 
      SheetView sheetView1 = new SheetView(){ TabSelected = true, WorkbookViewId = (UInt32Value)0U }; 

      sheetViews1.Append(sheetView1); 
      SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultRowHeight = 14.4D, DyDescent = 0.3D }; 

      SheetData sheetData1 = new SheetData(); 

      Row row1 = new Row(){ RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" }, DyDescent = 0.3D }; 

      Cell cell1 = new Cell(){ CellReference = "A1", StyleIndex = (UInt32Value)1U, DataType = CellValues.SharedString }; 
      CellValue cellValue1 = new CellValue(); 
      cellValue1.Text = "0"; 

      cell1.Append(cellValue1); 

      row1.Append(cell1); 

      sheetData1.Append(row1); 

      Hyperlinks hyperlinks1 = new Hyperlinks(); 
      Hyperlink hyperlink1 = new Hyperlink(){ Reference = "A1", Id = "rId1" }; 

      hyperlinks1.Append(hyperlink1); 
      PageMargins pageMargins1 = new PageMargins(){ Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D }; 

      worksheet1.Append(sheetDimension1); 
      worksheet1.Append(sheetViews1); 
      worksheet1.Append(sheetFormatProperties1); 
      worksheet1.Append(sheetData1); 
      worksheet1.Append(hyperlinks1); 
      worksheet1.Append(pageMargins1); 
      return worksheet1; 
     } 


    } 
} 
+0

我没有看到直接从Worksheet访问Cell对象的方法。我正在使用open xml sdk 2.0,并且据我所知,Cell对象 – amurra 2010-05-26 16:08:58

+0

上没有.Hyperlink属性,有些事情随着RTM 2.0而改变。见上面反映的例子。 – 2010-05-26 17:46:47

+0

是的,代码将工作,但我已经有一个现有的工作表,并希望添加超链接到已存在的单元格。 – amurra 2010-05-27 15:22:14

5

另一种可能性(我使用的)是使用Excel的HYPERLINK公式。我需要在每个单元格中创建单独的超链接,但单元格必须显示不同的文本(我必须在单元格中显示跟踪号码,但每个跟踪号码都有一个超链接到运营商的站点,并且必须处理多个运营商)。

一旦予实例化的单个电池,式中以这种方式施加到每个单元(有无疑众多方式):

// ... 
Cell cell1 = new Cell(){ CellReference = "A1", StyleIndex = (UInt32Value)1U, DataType = CellValues.InlineString }; 
CellValue cellValue1 = new CellValue(); 

CellFormula cellFormula1 = new CellFormula() { Space = SpaceProcessingModeValues.Preserve }; 
cellFormula1.Text = @"HYPERLINK(""http://www.theclash.com"", ""Radio Clash"")"; 
cellValue1.Text = "Radio Clash"; 
cell1.Append(cellFormula1); 
cell1.Append(cellValue1); 
// append cell, etc. 

以这种方式,我能够创建单独的超链接和文本每个单元格。顺便说一句,链接将以默认的字体颜色显示,除非您引用蓝色字体的样式。

希望这会有所帮助。

+0

不错的选择。为我工作。 – Jeff 2015-04-27 14:54:32

相关问题