ag-grid + valuegetter + row grouping - ag-grid

ag-grid valuegetter + row grouping, on cell click need to get params data.
In case of header & other cells except grouped row we are getting params data.
column definition of ag-grid looking like below:
const scopeOutCurrIndex = function (col, rSeg, isPVInColSegment) {
return function (params) {
return params.data;
 }
};
const colDefObj: any = {};
// for E-NG-GRID
colDefObj['rowGroup'] = true;
colDefObj['hide'] = true;
colDefObj.headerName = this.segLabelMap
? this.gridUtilService.getSegmentLabel(rSegments[i], this.segLabelMap)
: rSegments[i];
colDefObj["isRowSegment"] = true;
colDefObj["headerId"] = rSegments[i];
//Set width for column
colDefObj["width"] = this.calColumnWidth(colDefObj.headerName);
colDefObj["moduleId"] = moduleIds ? moduleIds[0] : moduleIds;
colDefObj.valueGetter = scopeOutCurrIndex(rSegments[i], rSegments, this.isPVInColSegment);

const scopeOutCurrIndex = function (col, rSeg, isPVInColSegment) {
return function (params) {
return params.node.allLeafChildren[0].data;}
};
We can get data from leaf children, ag-grid provide flexible to get data from leaf children.

Related

Associate the chart and table in devextreme

I want to associate the table and chart in devextreme. I want to filter the chart also filter the table. can you help me?
You can achieve this by using filter option of related datasource
function chartFilter(ChartInstance, ChartKey, KeyValue, ReloadChartsFunc) {
/*
ChartInstance = Instance of devExtreme Chart
ChartKey = filter by ChartKey Field
KeyValue = value of ChartKey
ReloadChartsFunc = Callback function to execute once filter the ds
*/
var searchOperator = "<>";
if (KeyValue != "")
searchOperator = psChart.option("quickSearchOption");
var ds = ChartInstance.getDataSource();
ds.filter(ChartKey, searchOperator, KeyValue);
ds.load().done(function (result) {
if (ReloadChartsFunc != undefined && result[0] != undefined && result[0] != null) {
ReloadChartsFunc(result[0])
}
});
}
You can do whatever you want to modify the above code according to your need.

Nesting Model Reports + Search Results

Seem like I'm not the first to investigate this. But not despairing yet :-)
The target state I'd like to reach is:
A recursion through Packages, where some of the nested Sub-Packages are glorified Linked Documents, and some are Grids rendering Search Results.
I like that Model Documents provide Search Tag values -- but I can't seem to nest the grids where I want them to show up.
Approach 1: Nested Model Documents
If I could nest Model Document elements, with their Search/Search Term tags, I would be sorted. I could have
Context:Package
Introduction:Package <- just renders a Linked Document attached to it
Systems Affected:Package <- just renders a Linked Document attached to it
Systems Affected:Model Document <- renders the results of a canned Search.
But EA appears to be designed to ignore the Model Document element.
Approach 2: SQL backed Template Fragment
I like the Model Document as it has Search/Search Term + all the Inclusion/Exclusion configuration options. But if I had to give that part up I am thinking of emulating as much as I can via SQL or script.
First attempt - using SQL and a nested set of Packages such as:
Context:Package
Introduction:Package <- just renders a Linked Document attached to it
Systems Affected:Package <- just renders a Linked Document attached to it
Systems Affected:Package<> <- renders the results of a SQL Search.
If the template uses a TemplateSelector it can spot the Package with a wellknown stereotype, and invoke a Template that is backed by SQL.
The SQL uses the Package's Keywords as the source of the Element type to search for.
SELECT
o.ea_guid AS [CLASSGUID],
o.Object_Type AS [CLASSTYPE],
o.PDATA5 AS [KEYWORDS],
o.Object_Type AS [Type],
o.Stereotype AS [Stereotype],
*
FROM t_object as O
WHERE O.Object_Type IN
(SELECT PDATA5 FROM t_object AS S where S.Object_ID = #OBJECTID#)
It works...barely.It's a bit hacky.
Searching off of Element Type is not going to be sufficient for production documents.
Approach 3: Script backed Template Fragment
If I can get a script running I suspect that I could leverage functionality that is already in the system.
Context:Package
Introduction:Package <- just renders a Linked Document attached to it
Systems Affected:Package <- just renders a Linked Document attached to it
Systems Affected:Package<> <- renders the results of a canned Search.
If the template uses a TemplateSelector it can spot the Package with a wellknown stereotype, and invoke a Template that is backed by a script.
The script I'm trying is:
var x = Repository.GetElementsByQuery("POC.Req", "Device");
return x;
But the report remains blank of those elements I need for the table.
Q: Does the returned Collection need transformation before it can be used?
Approach 4
I've heard that there is an approach to Render Document sections as PDF, and link to them as Linked Documents... Sounds Convoluted. Sounds like a wrong/magic approach.
Approach 5
Any other suggestions?
Thanks for the help.
Addendum
Just got approach 3 to work by converting the script results to xml before handing it back
The template's script now looks like
-- first pass ...I'll work on passing the ObjectId in a bit in order to get fancier.
ExecuteSearch("Simple", "Device")
and it invokes a script saved somewhere else as
!INC Local Scripts.EAConstants-JScript
/*
* Script Name:
* Author:
* Purpose:
* Date:
*/
function main()
{
return ExecuteSearch("Simple", "Device");
}
function ExecuteSearch(searchName, searchParam){
var x = Repository.GetElementsByQuery(searchName, searchParam);
//return x;
var xmlDOC = CreateReport(x);
var s = xmlDOC.xml;
Session.Output(s);
return s;
}
function CreateReport(entityCollection){
var xmlDOC = CreateXmlDOC();
var xmlRoot = AppendXmlChild(xmlDOC,"EADATA");
var xmlDataSet = AppendXmlChild(xmlDOC,"Dataset_0",xmlRoot);
var xmlData = AppendXmlChild(xmlDOC,"Data",xmlDataSet);
for(var i = 0;i<entityCollection.Count();i++){
var entity = entityCollection.GetAt(i);
var xmlRow = AppendXmlChild(xmlDOC,"Row",xmlData);
//AppendXmlChild(xmlDOC,"CLASSTYPE",xmlRow).Text = entity.Type;
AppendXmlChild(xmlDOC,"Guid",xmlRow).text = entity.ElementGUID;
AppendXmlChild(xmlDOC,"CLASSTYPE",xmlRow).text = entity.Type;
AppendXmlChild(xmlDOC,"CLASSGUID",xmlRow).text = entity.ElementGUID;
AppendXmlChild(xmlDOC,"Type",xmlRow).text = entity.Type;
AppendXmlChild(xmlDOC,"Stereotype",xmlRow).text = entity.Stereotype;
AppendXmlChild(xmlDOC,"Name",xmlRow).text = entity.Name;
AppendXmlChild(xmlDOC,"Object",xmlRow).text = entity.Name;
AppendXmlChild(xmlDOC,"Id",xmlRow).text = entity.ElementID;
AppendXmlChild(xmlDOC,"Scope",xmlRow).text = entity.Scope;
AppendXmlChild(xmlDOC,"Phase",xmlRow).text = entity.Phase;
AppendXmlChild(xmlDOC,"Status",xmlRow).text = entity.Status;
var noteElement = AppendXmlChild(xmlDOC,"Notes",xmlRow);//.text = entity.Notes;
noteElement.appendChild(xmlDOC.createCDATASection(entity.Notes));
AppendXmlChild(xmlDOC,"Keywords",xmlRow).text = entity.PDATA5;
}
return xmlDOC;
}
function CreateXmlDOC()
{
var xmlDOM;
try
{
xmlDOM = new ActiveXObject( "MSXML2.DOMDocument.4.0" );
}
catch(e)
{
xmlDOM = new ActiveXObject( "MSXML2.DOMDocument.6.0" );
}
xmlDOM.createProcessingInstruction("xml","version=\"1.0\"");
xmlDOM.validateOnParse = false;
xmlDOM.async = false;
return xmlDOM;
}
function AppendXmlChild(xmlDOM, xmlElementName, xmlParent, isCDATA){
if (!xmlParent){xmlParent = xmlDOM;}
var child = xmlDOM.createElement(xmlElementName);
xmlParent.appendChild(child);
return child;
}
main();
The script I used in the end is as follows. It now correctly investigates the element's tags for clues as how to proceed.
Hope it helps others.
!INC Local Scripts.EAConstants-JScript
/*
* Script Name:
* Author:
* Purpose:
* Date:
*/
//Only used for development
function devTest()
{
//With Child elements: {2255D8C8-F1BB-4069-BDAF-8B303D108C62}
//With SearchName: {919252E0-BDEB-4f26-A39F-C0E74382952A}
//With PackageGUID: {8543ED3B-EC39-4bf0-92C2-FD49A00C376B}
Session.Output ("DEVTEST");
var package = Repository.GetPackageByGuid("{8543ED3B-EC39-4bf0-92C2-FD49A00C376B}");
Session.Output("Package Name:" + package.Name);
Session.Output("Package Guid:" + package.PackageGUID);
Session.Output("Package Id:" + package.PackageID);
Session.Output("Package ElementId:" + package.Element.ElementID);
//Session.Output("Package Element Id:" + package.Element.ElementID);
//Use the Element associate to the Package, not the Package ID itself.
var packageElementId = package.Element.ElementID; //NOT: package.PackageID;
var xmlDoc=ExecuteSearch(packageElementId);
try {
Session.Output(xmlDoc.xml);
}catch (e){
Session.Output(e.message);
}
}
//Extracts from a given Package it's SearchName/SearchValue tags
//in order to do a search that mimicks a ModelDocument's way of
//generating a report.
function ExecuteSearch(elementId){
//Validation
if (!elementId){
Session.Output("Exiting: No elementId received.");
return;
}
var packageElement = Repository.GetElementByID(elementId);
if (!packageElement){
Session.Output("Exiting: No package with given elementId: " + elementId);
return;
}
try {
var xmlDOC = ExecuteSearch2(packageElement);
var xml = xmlDOC.xml;
return xml;
}catch (e){
Session.Output("ERROR: " + e.message);
}
return null;
}
function ExecuteSearch2(packageElement){
//Session.Output(packageElement.ElementGUID + ": '" + packageElement.Name + "' invoking ExecuteSearch(" + packageElement.ElementID + ")");
//Session.Output("Attribute 'Test': " + GetElementTaggedValue(packageElement,'Test'));
//Precendence is to search
//* Direct children,
//* by Package, recursively,
//* Package, single
//* Package
//First dibs: does this package have any direct elements?
//Get back to the package that is related to the Element before you count Elements:
var package = Repository.GetPackageByGuid(packageElement.ElementGUID);
var elementCollection = package.Elements;
if (elementCollection.Count()){
Session.Output("Package [" + packageElement.ElementGUID + "] has child Elements:"+ elementCollection.Count());
return CreateReportDoc(elementCollection);
}
//If package had no children, look at Attributes for reference to other package.
//At present, can't find an easy way to determine package Id from the EA GUI, so
//using the Guid.
var searchPackageGuid = GetElementTaggedValue(packageElement,'SearchPackageGUID');
if (!searchPackageGuid){
searchPackageGuid = GetElementTaggedValue(packageElement,'SearchPackageGuid');
}
if (searchPackageGuid){
//Session.Output("Package [" + packageElement.ElementGUID + "] has SearchPackageGuid:"+ searchPackageGuid);
return ExecuteSearchByPackageGuid(searchPackageGuid);
}
// //If I ever find a way to get a packageId:
var searchPackageId = GetElementTaggedValue(packageElement,'SearchPackageId');
if (searchPackageId){
//Session.Output("Package [" + packageElement.ElementGUID + "] has SearchPackageId:"+ searchPackageId);
return ExecuteSearchByPackageId(searchPackageId);
}
// //If searching by SQL:
var searchSQL = GetElementTaggedValue(packageElement,'SearchSQL');
if (searchSQL){
Session.Output("Package [" + packageElement.ElementGUID + "] has SearchSQL:"+ searchSQL);
return ExecuteSearchBySQL(searchSQL);
}
//Not pointing to a package, so maybe pointing to a canned search:
var searchName = GetElementTaggedValue(packageElement,'SearchName');
if (!searchName){
//Session.Output("No SearchName");
return;
}
var searchValue = GetElementTaggedValue(packageElement,'SearchValue');
//Session.Output("Package [" + packageElement.ElementGUID + "] has SearchName/Value:"+ searchName + "/" + searchValue);
return ExecuteSearchBySearchName(searchName, searchValue);
}
//Mimicks functionality of a ModelDocument that searches by canned SearchName/SearchValue.
function ExecuteSearchBySearchName(searchName, searchValue){
var elementCollection = Repository.GetElementsByQuery(searchName, searchValue);
//return x;
return CreateReportDoc(elementCollection);
}
function ExecuteSearchByPackageGuid(packageGuid){
var package = Repository.GetPackageByGuid(packageGuid);
return ExecuteSearch2(package.Element);
}
function ExecuteSearchBySQL(searchSQL){
var elementCollection = Repository.GetElementSet(searchSQL, 2);
}
function HOLD_ExecuteSearchBySet(idList){
var elementCollection = Repository.GetElementsSet(idList);
//return x;
return CreateReportDoc(elementCollection);
}
//Iterate through the elements and convert to an Xml Document
//suitable for use by a Script backed Template:
function CreateReportDoc(elementCollection){
var xmlDOC = CreateXmlDOC();
var xmlData = CreateXmlReport(xmlDOC);
for(var i = 0;i<elementCollection.Count();i++){
//For each Element, create a new row:
var xmlRow = AppendXmlChild(xmlData,"Row");
//And embed the specific element:
var element = elementCollection.GetAt(i);
CreateReportRow(xmlRow, element);
}
return xmlDOC;
}
function CreateReportRow(xmlRow, element){
//And attach child property elements.
//For hairy ones, add them as a CDATA.
//AppendXmlChild(xmlDOC,"CLASSTYPE",xmlRow).Text = element.Type;
AppendXmlChild(xmlRow,"Guid").text = element.ElementGUID;
AppendXmlChild(xmlRow,"CLASSTYPE").text = element.Type;
AppendXmlChild(xmlRow,"CLASSGUID").text = element.ElementGUID;
AppendXmlChild(xmlRow,"Type").text = element.Type;
AppendXmlChild(xmlRow,"Stereotype").text = element.Stereotype;
AppendXmlChild(xmlRow,"Name").text = element.Name;
AppendXmlChild(xmlRow,"Object").text = element.Name;
AppendXmlChild(xmlRow,"Id").text = element.ElementID;
AppendXmlChild(xmlRow,"Scope").text = element.Scope;
AppendXmlChild(xmlRow,"Phase").text = element.Phase;
AppendXmlChild(xmlRow,"Status").text = element.Status;
AppendXmlChild(xmlRow,"Keywords").text = element.PDATA5;
//Notes need wrapping as CDATA
var noteElement = AppendXmlChild(xmlRow,"Notes");//.text = entity.Notes;
noteElement.appendChild(xmlRow.ownerDocument.createCDATASection(element.Notes));
//Now get tags:
AppendXmlChild(xmlRow,"Tags.ID").text = GetElementTaggedValue(element,"ID");
AppendXmlChild(xmlRow,"Tags.Type").text = GetElementTaggedValue(element,"Type");
AppendXmlChild(xmlRow,"Tags.Category").text = GetElementTaggedValue(element,"Category");
AppendXmlChild(xmlRow,"Tags.Traceability").text = GetElementTaggedValue(element,"Traceability");
return xmlRow;
}
//helper function to create an empty xml document
function CreateXmlDOC()
{
var xmlDOM;
try
{
xmlDOM = new ActiveXObject( "MSXML2.DOMDocument.4.0" );
}
catch(e)
{
xmlDOM = new ActiveXObject( "MSXML2.DOMDocument.6.0" );
}
xmlDOM.createProcessingInstruction("xml","version=\"1.0\"");
xmlDOM.validateOnParse = false;
xmlDOM.async = false;
return xmlDOM;
}
//helper function to create the beginning of an xml document
//suitable to render the results of a search:
function CreateXmlReport(xmlDOC){
var xmlRoot = AppendXmlChild(xmlDOC,"EADATA");
var xmlDataSet = AppendXmlChild(xmlRoot,"Dataset_0");
var xmlData = AppendXmlChild(xmlDataSet,"Data");
return xmlData;
}
//helper function to attach a new child xml element to a parent xml element
function AppendXmlChild(xmlParent, xmlElementName, isCDATA){
var xmlDocument = xmlParent.ownerDocument;
if (!xmlDocument){xmlDocument = xmlParent}
var child = xmlDocument.createElement(xmlElementName);
xmlParent.appendChild(child);
return child;
}
//Gets an Element's tag. Eats exception if Tag does not exist.
function GetElementTaggedValue(element, tagName){
var tag;
try {
tag = element.TaggedValues.GetByName(tagName);
}
catch (e) {
}
if (!tag){return;}
var result = tag.Value;
return result;
}
function ConvertPackageIdToBranchId(packageId){
var package = Repository.GetPackageByID(objectId);
if (!package){return;}
var packages = [package];
packages.concat(ConvertPackageToBranch(package));
var result=[];
for(var i=0;i<packages.length;i++){
result.push(packages[i].PackageID);
}
return result;
}
function ConvertPackageToBranch(package){
var result = [];
for (var i=0;i<package.Packages.Count();i++){
var childPackage = package.Packages.GetAt(i);
result.push(childPackage);
result.concat(ConvertPackageToBranch(childPackage));
}
return result;
}
//devTest();

Updating an HTML table in d3.js using a reusable chart

I have this reusable pattern to create a table, inspired by http://bl.ocks.org/3687826, and I have two questions about it.
This is the function:
d3.table = function(config) {
var columns = [];
var tbl = function(selection) {
if (columns.length == 0) columns = d3.keys(selection.data()[0][0]);
console.log(columns)
// Creating the table
var table = selection.append("table");
var thead = table.append("thead");
var tbody = table.append("tbody");
// appending the header row
var th = thead.selectAll("th")
.data(columns)
th.enter().append("th");
th.text(function(d) { return d });
th.exit().remove()
// creating a row for each object in the data
var rows = tbody.selectAll('tr')
.data(function(d) { return d; })
rows.enter().append("tr");
rows.attr('data-row',function(d,i){return i});
rows.exit().remove();
// creating a cell for each column in the rows
var cells = rows.selectAll("td")
.data(function(row) {
return columns.map(function(key) {
return {key:key, value:row[key]};
});
})
cells.enter().append("td");
cells.text(function(d) { return d.value; })
.attr('data-col',function(d,i){return i})
.attr('data-key',function(d,i){return d.key});
cells.exit().remove();
return tbl;
};
tbl.columns = function(_) {
if (!arguments.length) return columns;
columns = _;
return this;
};
return tbl;
};
This table can be called as follows:
/// new table
var t = d3.table();
/// loading data
d3.csv('reusable.csv', function(error,data) {
d3.select("body")
.datum(data.filter(function(d){return d.price<850})) /// filter on lines
.call(t)
});
where the reusable.csv file is something like this:
date,price
Jan 2000,1394.46
Feb 2000,1366.42
Mar 2000,1498.58
Apr 2000,1452.43
May 2000,1420.6
Jun 2000,1454.6
Jul 2000,1430.83
Aug 2000,1517.68
Sep 2000,1436.51
and the number of columns can be updated by
t.columns(["price"]);
d3.select("body").call(t);
The problem is that another table with thead and tbody is created while updating, because the creation of the table is inside the function.
How can I say "create the table only one time, then update"?
Another question is: how can I filter the lines using a method inside the function?
The problem is with these three lines of code:
// Creating the table
var table = selection.append("table");
var thead = table.append("thead");
var tbody = table.append("tbody");
which always appends new table, thead, and tbody elements to your document. Here's how you can do this conditionally, only when these elements don't already exist (the example you cite creates its div.header element similarly):
selection.selectAll('table').data([0]).enter().append('table');
var table = selection.select('table');
table.selectAll('thead').data([0]).enter().append('thead');
var thead = table.select('thead');
table.selectAll('tbody').data([0]).enter().append('tbody');
var tbody = table.select('tbody');
The selectAll().data([0]).enter().append() pattern conditionally creates a single element if it isn't found. The cited example used data([true]) but any array with a single element will do.
To filter the nested data from within your function, change your call to data() and pass a filtered subset of the selection data like this:
var rows = tbody.selectAll('tr').data(tbody.data()[0].filter(function(d) {
return d.price > 1400;
}));
Good luck!

Devexpress xtraChart How to assign x and y values?

I have values in datasource and there is no problem with datasource. I have to assign X and Y values to the chart. Chart throws an error and says there is no column with named "TotalInboundArrivals".
ChartControl chart = new ChartControl();
chart.Location = new Point(38, 301);
chart.Size = new Size(789, 168);
Series series = new Series("Series1", ViewType.Bar);
chart.Series.Add(series);
series.DataSource = ds;
series.ArgumentScaleType = ScaleType.Numerical;
series.ArgumentDataMember = "TotalInboundArrivals"; //throws error here
series.ValueScaleType = ScaleType.Numerical;
series.ValueDataMembers.AddRange(new string[] { "StartTime" }); //throws error here
((SideBySideBarSeriesView)series.View).ColorEach = true;
((XYDiagram)chart.Diagram).AxisY.Visible = true;
chart.Legend.Visible = true;
chart.Visible = true;
chart.Dock = DockStyle.Fill;
xtraTabPage1.Controls.Add(chart);
Where is my Problem? Any Suggestions?
Have you went through Series.DataSource Property. You are making the mistake of assigning DataSet as DataSource to series. Think about it, how could it search columns in Data Source. Try to assign Ds.Tables["TableName"] as the datasource.
Creating DataSource Table
private DataTable CreateChartData(int rowCount) {
// Create an empty table.
DataTable table = new DataTable("Table1");
// Add two columns to the table.
table.Columns.Add("Argument", typeof(Int32));
table.Columns.Add("Value", typeof(Int32));
// Add data rows to the table.
Random rnd = new Random();
DataRow row = null;
for (int i = 0; i < rowCount; i++) {
row = table.NewRow();
row["Argument"] = i;
row["Value"] = rnd.Next(100);
table.Rows.Add(row);
}
Specifying Series properties corresponding to datasource
Series series = new Series("Series1", ViewType.Bar);
chart.Series.Add(series);
// Generate a data table and bind the series to it.
series.DataSource = CreateChartData(50);
// Specify data members to bind the series.
series.ArgumentScaleType = ScaleType.Numerical;
series.ArgumentDataMember = "Argument";
series.ValueScaleType = ScaleType.Numerical;
series.ValueDataMembers.AddRange(new string[] { "Value" });
Check the Examples and go through the Creating Charts -> Providing Data section to better understand it.
Reference
Hope this helps.

Add Hyperlink to Cell in Excel 2007 Using Open XML SDK 2.0

I can't seem to find any documentation or code samples on how to add a hyperlink to a cell in Excel 2007 using the Open XML SDK 2.0. I am using the following code, but is there a step I am missing?
WorksheetPart workSheetPart = ExcelUtilities.GetWorkSheetPart(mWorkBookPart, "Program");
workSheetPart.AddHyperlinkRelationship(new Uri("http://www.google.com", UriKind.Absolute), true);
workSheetPart.Worksheet.Save();
mWorkBookPart.Workbook.Save();
Then when I try and open the Excel document it says the file is corrupted because the Relationship Id for the hyperlink cannot be found. How do you setup or create that Relationship Id?
Another possibility, (which I used), is to use the HYPERLINK formula for Excel. I needed to create individual hyperlinks in each cell, yet the cells had to display different text, (I had to display tracking numbers in the cells yet have a hyperlink for each tracking number to the carrier's site and had to handle multiple carriers).
Once I instantiated an individual cell, the formula was applied in this manner to each cell (there are undoubtedly numerous way):
// ...
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.
In this way, I was able to create individual hyperlinks and text for each cell. By the way, the links will appear with the default font color unless you reference a style with blue font.
Hope this helps.
I was able to add a hyperlink to a cell using System.IO.Packaging code:
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;
}
I then translated this code using the Open XML SDK 2.0 and it doesn't work. It seems the AddHyperlinkRelationship method doesn't actually add the relationship to the .rels file. I'm not sure why, but it sure seems like a bug to me.
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();
}
You should be adding it to an object that accepts hyperlinks, such as a cell, instead of the worksheet. Something like this should work for you:
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;
}
}
}
Easiest way is to use the HyperLink formular, but the links aren't blue by default, this is why the styleIndex is set.
private Cell BuildHyperlinkCell(string url) =>
new Cell
{
DataType = new EnumValue<CellValues>(CellValues.String),
CellFormula = new CellFormula($"HyperLink(\"{url}\")"),
StyleIndex = 4u
};
Adding the styling to the workbook:
http://www.dispatchertimer.com/tutorial/how-to-create-an-excel-file-in-net-using-openxml-part-3-add-stylesheet-to-the-spreadsheet/