Excel导出数据添加超链接,打开本地图⽚
//将DataTable导出到Excel,并为其中⼀列添加超链接,点击链接打开本地图⽚
public static bool Create(DataTable dt, string filePath, bool IsOverWrite = true, bool IsAppendTitle = true, string[] Headers = null, string fileName = "", string blobUrl = "", bool isLinux = false, string contaner = "", string fileUrl = {
try
{
dt ??= new DataTable();
//创建Excel⽂件的对象
var book = new HSSFWorkbook();
//添加⼀个sheet
var sheet1 = book.CreateSheet("Sheet1");
#region//书写标题
if (IsAppendTitle)
{
图片链接怎么生成if (Headers == null || Headers.Length == 0) { Headers = dt.GetColumnNames().ToArray(); }
//给sheet1添加第⼀⾏的头部标题
var row1 = sheet1.CreateRow(0);
for (var i = 0; i < Headers.Length; i++)
{
row1.CreateCell(i).SetCellValue(Headers[i]);
}
}
#endregion
#region//填充数据
var k = IsAppendTitle ? 1 : 0;
for (var i = 0; i < dt.Rows.Count; i++)
{
//创建数据⾏
var rowtemp = sheet1.CreateRow(k);
rowtemp.CreateCell(0).SetCellValue((k).ToString());
k++;
//填充数据
for (var j = 0; j < dt.Columns.Count; j++)
{
var value = dt.Rows[i][j].ToString();
var cell = rowtemp.CreateCell(j);
var name = dt.Columns[j].ColumnName;
//需要添加超链接的列
if (name == "FILEPATH")
{
//⽹络图⽚下载到本地
value = DownlodImg(value);
//添加超链接
var link = new HSSFHyperlink(HyperlinkType.File) { Address = value };
cell.Hyperlink = link;
}
cell.SetCellValue(value);
}
}
#endregion
var file = new FileInfo(DoPath.GetFullPath(filePath + fileName));
if (file.Exists && !IsOverWrite)
{
file.Delete();
}
#region//写⼊⽂件
using var ms = new MemoryStream();
book.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
using var fileStream = new FileStream(file.FullName, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
var bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();
ms.Close();
#endregion
file.Refresh();
return file.Exists;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
//⽹络图⽚下载到本地
public static string DownlodImg(string imagePath)
{
var localPath = @"\ticket\image\";
var filePath = localPath;// AppDomain.CurrentDomain.BaseDirectory + @"";
try
{
var name = imagePath.TrimStart('/').Replace("\\", "/");
var fileUrl = "图⽚⽹络地址";
var request = WebRequest.Create(fileUrl);
var response = request.GetResponse();
var reader = response.GetResponseStream();
var file = new FileInfo(DoPath.GetFullPath(filePath));
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
filePath += imagePath[(imagePath.LastIndexOf(@"/", StringComparison.Ordinal) + 1)..] + ".jpg";
var writer = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
var buff = new byte[1024];
var c = 0; //实际读取的字节数
while (reader != null && (c = reader.Read(buff, 0, buff.Length)) > 0)
{
writer.Write(buff, 0, c);
}
writer.Close();
writer.Dispose();
if (reader != null)
{
reader.Close();
reader.Dispose();
}
response.Close();
}
catch (Exception ex)
{
return"";
}
return@"..\" + filePath;
}
⽂件夹结构
点击excel中的图⽚链接会⾃动打开⽂件夹中的图⽚
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论