【问题标题】:Copying hyperlinks from a cell to another with NPOI使用 NPOI 将超链接从一个单元格复制到另一个单元格
【发布时间】:2017-02-18 01:41:22
【问题描述】:

我正在尝试将某些数据从工作表复制到另一个工作表,但有些单元格是简单的字符串,有些是超链接。 如果我在字符串上使用 StringCellValue 就可以了,但是我还没有找到一种方法将超链接从原始工作表复制到我正在构建的新工作表中。

对于新工作表的构建和数据复制,我使用的是 NPOI。

//更新 我添加了插入超链接的代码,但是当我运行程序时,它显示以下异常:对象引用未设置为对象的实例。

这是我的代码:

  using (FileStream fs = new FileStream(@"C:\Users\File.xlsx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                Console.WriteLine("Time to wait....");
                templateWorkbook = new XSSFWorkbook(fs);

            }
              row.GetCell(6).SetCellValue(sheettoget.GetRow(1).GetCell(13).StringCellValue);
            var sourceLink = sheettoget.GetRow(1).GetCell(13).Hyperlink;


                    if(sourceLink != null)
              {
                        Console.WriteLine("Inserting first Juice session...");
                        var targetLink = new XSSFHyperlink(sourceLink.Type);

                        targetLink.Address = sourceLink.Address;
                       }

                        row.GetCell(6).Hyperlink = targetLink; 
                        row.GetCell(6).CellStyle = sheettoget.GetRow(1).GetCell(13).CellStyle;

【问题讨论】:

    标签: c# .net excel hyperlink npoi


    【解决方案1】:

    您可以像这样复制超链接,其中sourceCell 是您要复制的单元格,targetCell 是您要复制到的单元格:

        targetCell.SetCellValue(sourceCell.StringCellValue);
        var sourceLink = sourceCell.Hyperlink;
        if (sourceLink != null)
        {
            var targetLink = new XSSFHyperlink(sourceLink.Type);
            targetLink.Address = sourceLink.Address;
            targetCell.Hyperlink = targetLink;
    
            // also copy the cell style to ensure the copied link still looks like a link
            targetCell.CellStyle = sourceCell.CellStyle;
        }
    

    【讨论】:

    • 嘿,再次感谢您的帮助 :D 但我明白了:对象引用未设置为对象的实例
    • 在上面的代码中,最后两行应该是 inside if (sourceLink != null) 的右大括号,如我的回答所示。如果在那之后您仍然收到 NullReferenceException,您需要调试并找出导致错误的行。一旦你知道了,你可以添加一个空检查。见What is a NullReferenceException, and how do I fix it?