EPPlus超链接到另一张表格中的单元格

时间:2017-01-24 23:24:07

标签: c# excel epplus epplus-4

我正在努力将添加到另一个列表的超链接添加到我生成的excel文件中。我试过这样的话:

ws.Cells[1, 1].Formula="HYPERLINK(\"[#]'sheetName'!R4C1\";\"linktext\")"
ws.Cells[1, 1].Formula="HYPERLINK(\"#'sheetName'!R4C1\";\"linktext\")"
ws.Cells[1, 1].FormulaR1C1="HYPERLINK(\"[#]'sheetName'!R4C1\";\"linktext\")"
ws.Cells[1, 1].FormulaR1C1="HYPERLINK(\"#'sheetName'!R4C1\";\"linktext\")"

在excel 365(完全脱机应用程序)中打开生成的excel文件后,我得到的消息是文件中存在错误,并且我使用此超链接公式的所有单元格都是空的。

错误消息是:

we found a problem with some content in FILENAME do you want us to try to recover as much as we can

如何让它发挥作用?

此外,当我手动将相同的公式放入单元格时,它也能正常工作。

完整代码:

using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelHyperlinkTest
{
    class Program
    {
        static void Main(string[] args)
        {
            MemoryStream excelStream = new MemoryStream();
            ExcelPackage excelFile = new ExcelPackage(excelStream);

            ExcelWorksheet wsSrc = excelFile.Workbook.Worksheets.Add("src");
            ExcelWorksheet wsTgt = excelFile.Workbook.Worksheets.Add("tgt");

            wsSrc.Cells[1, 1].Formula = string.Format("HYPERLINK(\"#'{0}'!R{1}C{2}\";\"{3}\")", "tgt", 2, 5, "test"); //FormulaR1C1

            excelFile.Save();
            excelStream.Position = 0;

            using (FileStream file = new FileStream("c:\\linkTest.xlsx", FileMode.Create, System.IO.FileAccess.Write))
            {
                byte[] bytes = new byte[excelStream.Length];
                excelStream.Read(bytes, 0, (int)excelStream.Length);
                file.Write(bytes, 0, bytes.Length);
                excelStream.Close();
            }
        }
    }
}

3 个答案:

答案 0 :(得分:6)

这有效

wsSrc.Cells[1, 6].Value = "test3";
            Uri url = new Uri("#'tgt'!B5", UriKind.Relative);
            wsSrc.Cells[1, 6].Hyperlink = url;

答案 1 :(得分:0)

如果工作表存在于同一个excel文件中,并且任何人都使用EPPlus库,则以下代码可能会帮助他们:

int rowCount=<your specific row> 
ws.Cells[rowCount, 6].Hyperlink = new ExcelHyperLink((char)39 + "Name of your sheet" + 
(char)39 + "!A1(specific cell on that sheet)", "Link text");

答案 2 :(得分:0)

这将相对于当前工作簿链接到工作簿(workbookPath)的工作表(sheetName)中的B5,并将链接设置为超链接格式

using (ExcelRange rng = xlsheetSummary.Cells[1, 1])
{
    var namedStyle = xlsheetSummary.Workbook.Styles.NamedStyles.FirstOrDefault(o=> o.Name == "HyperLink");

    namedStyle.Style.Font.UnderLine = true;
    rng.StyleName = namedStyle.Name;

    rng.Value = ws.Name;
    Uri link = new Uri($"{workbookPath}#'{sheetName}'!B5", UriKind.Relative);
    namedStyle.Style.Font.Color.SetColor(Color.Blue);                                 
    rng.Hyperlink = link;
}