OpenXML如何添加指向另一个工作表的超链接

时间:2017-07-07 17:05:32

标签: c# .net excel hyperlink openxml

我正在寻找如何向单元格添加超链接的示例。 似乎它不像添加文本那么容易。

我得到了生成正确XML的代码,但是在excel链接中没有出现

    private SheetData PopulateSheetWithData(SheetData sheetData, IList<Event> events, SpreadsheetDocument document)
    {
        int errorIndex = 0;
        foreach (var @event in events)
        {
            errorIndex++;

            Hyperlinks hyperlinks = new Hyperlinks();
            Hyperlink hyperlink = new Hyperlink()
            {
                Location = "UniqueError_" + errorIndex + "!A1",
                Display = @event.LOG_CORR_KEY,
                Reference = "A"+(errorIndex+1),
                Id = "UniqueError_" + errorIndex
            };
            hyperlinks.AppendChild(hyperlink);
            sheetData.AppendChild(hyperlinks);
        }
        return sheetData;
    }

我做错了吗? 我发现了this文章如何添加hyperLink,但看起来它太复杂了。对这个问题有任何帮助吗?

2 个答案:

答案 0 :(得分:2)

所以经过一段时间将我的头撞到桌子上后,我决定专注于我的OpenXML Excell调查,我成功了!

我找到了一个解决方法,如何向excell文件插入超链接,甚至更多,现在我的程序可以创建多个工作表,其数量取决于我的dataObject。 我很兴奋,我想与大家分享我的成就。

首先,您需要创建SpreadSheetDocument,因此我创建了一个方法CreatePackage并将其作为参数传递给filePath以及我的DataObject

public void CreatePackage(string filePath, List<DataObject> data)
{
    using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook)
    )
    {
        CreateParts(document, data);
    }
 }

CreateParts方法接受 SpreadsheetDocument DataObject

private void CreateParts(SpreadsheetDocument document, List<DataObject> data)
    {
        ExtendedFilePropertiesPart extendedFilePropertiesPart = document.AddNewPart<ExtendedFilePropertiesPart>();
        extendedFilePropertiesPart.Properties = new Properties();

        WorkbookPart workbookPart = document.AddWorkbookPart();
        //Create new sheet for every Unique error
        GenerateWorkbookPart(workbookPart,data.Count);
        //generates new SheetPart for every sheet
        GenerateWorkSheetsParts(workbookPart,data);

    }

我无法找到为什么以及ExtendedFilePropertiesPart如何依赖Excell中的HyperLink,但我确信没有这个超链接也不起作用,即使Excell文件也会生成损坏。

接下来我们需要为工作簿创建工作簿 工作簿我们需要创建一个表格保留所有表格。对于每个表单,我们还需要创建 WorkSheetPart ,但是我会稍后再回来。现在:

private void GenerateWorkbookPart(WorkbookPart workbookPart, int dataCount)
        {

            Workbook workbook = new Workbook();
            Sheets sheets = new Sheets();
            Sheet sheet = new Sheet();
            for (int i = 1; i < dataCount+2; i++)
            {
                var relId = "rId" + i;
                if (i == 1)
                {
                    sheet = new Sheet()
                    {
                        Name = "Main",
                        SheetId = (uint) i,
                        Id = relId
                    };
                }
                else
                {
                    sheet = new Sheet()
                    {
                        Name = "Unique" + (i-1),
                        SheetId = (uint)i,
                        Id = relId
                    };
                }

                sheets.AppendChild(sheet);
            }
            workbook.AppendChild(sheets);
            workbookPart.Workbook = workbook;
        }

为什么我要在总数上加+2?因为首先,由于某种原因,工作表的RelationshipId( Id )不能为0所以我需要从1和2开始,我的excell的第一页是导航页面,所以我也跳过它。 / p>

为我的文档创建WorkBookPart后,我将开始为每个工作表创建 WorkSheetPart 并使用数据填充它。

private void GenerateWorkSheetsParts(WorkbookPart workbookPart, List<DataObject> data)
        {
            for (int i = 1; i < data.Count+2; i++)
            {
                var relId = "rId" + i;
                if (i == 1)
                {
                    WorksheetPart workSheetPart = workbookPart.AddNewPart<WorksheetPart>(relId);
                    GenerateWorkSheetPartContent(workSheetPart, i, data);
                }
                else
                {
                    WorksheetPart workSheetPart = workbookPart.AddNewPart<WorksheetPart>(relId);
                    GenerateWorkSheetPartContent(workSheetPart, i, data[i-2].NestedObject);
                }

            }
        }

 private void GenerateWorkSheetPartContent(WorksheetPart worksheetPart,int indexer, List<NestedObject> data)
        {

            Worksheet worksheet = new Worksheet();
            SheetData sheetData = new SheetData();
            Hyperlinks hyperlinks = new Hyperlinks();

            if (indexer == 1)
            {
                sheetData.AppendChild(ConstructHeader("Unique errors", "Count"));

                foreach (var @event in data)
                {
                    indexer++;
                    Row row = new Row();
                    row.Append(ConstructCell(@event.ErrorMessage, "A" + indexer, CellValues.String), ConstructCell(@event.ListOfErrorsObject.Count.ToString(), CellValues.Number));
                    sheetData.AppendChild(row);
                    Hyperlink hyperlink = new Hyperlink()
                    {
                        Reference = "A" + indexer,
                        Location = "Unique" + (indexer - 1)+"!A1",
                        Display = "Unique" + indexer
                    };
                    hyperlinks.AppendChild(hyperlink);
                }
                worksheet.Append(sheetData, hyperlinks);
                worksheetPart.Worksheet = worksheet;
            }
            else
            {
                worksheet.AppendChild(sheetData);
                worksheetPart.Worksheet = worksheet;
            }
        }

索引器 - 随着我的对象一个接一个地移动,我可以确保Indexer与 rId 数字相同,也等于第一列行号。

我还做了一些帮助 ConstructHeader ,它在第一行构造标题,它需要String和 ConstructCell 的参数,这有助于更快地构建我可以附加到行的单元格。它还有一个用于构造单元格的重载,它应该带有超链接。

        private Row ConstructHeader(params string[] headers)
    {
        Row row = new Row();
        foreach (var header in headers)
        {
            row.AppendChild(ConstructCell(header, CellValues.String));
        }
        return row;
    }

    private Cell ConstructCell(string value, CellValues dataType)
    {
        return new Cell()
        {
            CellValue = new CellValue(value),
            DataType = new EnumValue<CellValues>(dataType),
        };
    }
    private Cell ConstructCell(string value, string cellReference, CellValues dataType)
    {
        return new Cell()
        {
            CellReference = cellReference,
            CellValue = new CellValue(value),
            DataType = dataType,
        };
    }

要点: 此代码将创建Excell文档,其中第一个Sheet作为导航,其他工作表包含DataObject的填充数据。我希望这会对某人有所帮助。 另外如果您有任何意见或反馈 - 请分享我想听听。

答案 1 :(得分:0)

这对我有用,并将“test.xlsx”的 Sheet1 中的 C1 链接到 Sheet2 中的 A10

static void AddHyperlink()
    {

        var filePath = "test.xlsx";

        // C1 in Sheet1
        var sheetName1 = "Sheet1";
        var column = "C";
        var row = 1;

        // Link to A10 in Sheet2
        var pathToOtherFile = filePath;
        var sheetName2 = "Sheet2";
        var cellRef = "A10";

        using (var document = SpreadsheetDocument.Open(filePath, true))
        {
            WorkbookPart wbPart = document.WorkbookPart;



            var sheets = document.WorkbookPart.Workbook.Sheets.Cast<Sheet>().ToList();



            var sheet = sheets.Where(x => x.Name == sheetName1).FirstOrDefault();

            string relationshipId = sheets.First().Id.Value;
            //get the worksheetpart by Id
            WorksheetPart worksheetPart = (WorksheetPart)wbPart.GetPartById(relationshipId);
            var worksheet = worksheetPart.Worksheet;


            Cell cell = GetCell(worksheet, column, row);
            var s = cell.LastChild;

            var cell1 = cell;

            CellFormula cellFormula1 = new CellFormula() { Space = SpaceProcessingModeValues.Preserve };
            cellFormula1.Text = $"HYPERLINK(\"[{pathToOtherFile}]{sheetName2}!{cellRef}\", \"Radio Clash\")";
            cell1.CellFormula = cellFormula1;

        }

    }


    private static Cell GetCell(Worksheet worksheet, string columnName, int rowIndex)
    {
        Row row = GetRow(worksheet, rowIndex);

        if (row == null)
            return null;

        return row.Elements<Cell>().Where(c => string.Compare
               (c.CellReference.Value, columnName +
               rowIndex, true) == 0).First();
    }


    // Given a worksheet and a row index, return the row.
    private static Row GetRow(Worksheet worksheet, int rowIndex)
    {
        return worksheet.GetFirstChild<SheetData>().
          Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
    }

如果要使用自引用(不引用另一个文件),可以使用:

    cellFormula1.Text = $"=HYPERLINK(\"[\" & MID(CELL(\"filename\"),SEARCH(\"[\",CELL(\"filename\"))+1, SEARCH(\"]\",CELL(\"filename\"))-SEARCH(\"[\",CELL(\"filename\"))-1) &\"]{sheetName2}!{cellRef}\", \"Radio Clash\")";

代替:

cellFormula1.Text = $"HYPERLINK(\"[{pathToOtherFile}]{sheetName2}!{cellRef}\", \"Radio Clash\")";