使用 NPOI 将超链接从一个单元格复制到另一个单元格
Copying hyperlinks from a cell to another with NPOI
我正在尝试将某些数据从 sheet 复制到另一个,但有些单元格是简单的字符串,有些是超链接。
如果我在字符串上使用 StringCellValue 就可以了,但是我还没有找到一种方法可以将超链接从原始 sheet 复制到我正在构建的新超链接中。
为了构建新的 sheet 和进行数据复制,我正在使用 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;
您可以像这样复制超链接,其中 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;
}
我正在尝试将某些数据从 sheet 复制到另一个,但有些单元格是简单的字符串,有些是超链接。 如果我在字符串上使用 StringCellValue 就可以了,但是我还没有找到一种方法可以将超链接从原始 sheet 复制到我正在构建的新超链接中。
为了构建新的 sheet 和进行数据复制,我正在使用 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;
您可以像这样复制超链接,其中 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;
}