I am trying to copy certain data from a sheet to another, but some cells are simple strings and some are hyperlinks. If I use StringCellValue on the strings one it's ok, but I haven't found a method to copy the hyperlinks from the original sheet into the new one that I am constructing.
For the construction of the new sheet and for data copying I am using NPOI.
//UPDATE I have added the code to insert the hyperlinks but when I run the program it shows the following exception: Object reference not set to an instance of an object.
Here is my code:
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;
You can copy a hyperlink like this, where sourceCell
is the cell you are copying from, and targetCell
is the cell you are copying to:
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;
}